1. Project Overview & Quickstart (PaddlePaddle/serving)
File: README.md
(简体中文|English)
文档
部署
此章节引导您完成安装和部署步骤,强烈推荐使用Docker部署Paddle Serving,如您不使用docker,省略docker相关步骤。在云服务器上可以使用Kubernetes部署Paddle Serving。在异构硬件如ARM CPU、昆仑XPU上编译或使用Paddle Serving可阅读以下文档。每天编译生成develop分支的最新开发包供开发者使用。
- 使用 Docker 安装 Paddle Serving
- Linux 原生系统安装 Paddle Serving
- 源码编译安装 Paddle Serving
- Kuberntes集群部署 Paddle Serving
- 部署 Paddle Serving 安全网关
- 异构硬件部署[ARM CPU、百度昆仑、华为昇腾、海光DCU、Jetson]
- Docker 镜像列表
- 下载 Python Wheels
使用
安装Paddle Serving后,使用快速开始将引导您运行Serving。具体步骤如下:
第一步,调用模型保存接口,生成模型参数配置文件(.prototxt)用以在客户端和服务端使用;
第二步,阅读配置和启动参数并启动服务;
第三步,根据API和您的使用场景,基于SDK编写客户端请求,并测试推理服务。您想了解跟多特性的使用场景和方法,请详细阅读以下文档。
- 快速开始
- 保存用于Paddle Serving的模型和配置
- 配置和启动参数的说明
- RESTful/gRPC/bRPC API指南
- 低精度推理
- 常见模型数据处理
- 普罗米修斯
- 设置 TensorRT 动态shape
- C++ Serving 概述
- Python Pipeline 概述
- 客户端SDK
- 大规模稀疏参数索引服务
开发者
为Paddle Serving开发者,提供自定义OP,变长数据处理。
模型库
Paddle Serving与Paddle模型套件紧密配合,实现大量服务化部署,包括图像分类、物体检测、语言文本识别、中文词性、情感分析、内容推荐等多种类型示例,以及Paddle全链条项目,共计46个模型。
更多模型示例进入模型库
社区
您想要同开发者和其他用户沟通吗?欢迎加入我们,通过如下方式加入社群
微信
- 微信用户请扫码
- 飞桨推理部署交流群(Group No.:697765514)
贡献代码
如果您想为Paddle Serving贡献代码,请参考 Contribution Guidelines(English)
- 感谢 @w5688414 提供 NLP Ernie Indexing 案例
- 感谢 @loveululu 提供 Cube python API
- 感谢 @EtachGu 更新 docker 使用命令
- 感谢 @BeyondYourself 提供grpc教程,更新FAQ教程,整理文件目录。
- 感谢 @mcl-stone 提供faster rcnn benchmark脚本
- 感谢 @cg82616424 提供unet benchmark脚本和修改部分注释错误
- 感谢 @cuicheng01 提供PaddleClas的11个模型
- 感谢 @Jiaqi Liu 新增list[str]类型输入的预测支持
- 感谢 @Bin Lu 提供PP-Shitu C++模型示例
反馈
如有任何反馈或是bug,请在 GitHub Issue提交
License
File: CMakeLists.txt
Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
cmake_minimum_required(VERSION 3.0)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
set(PADDLE_SERVING_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
set(PADDLE_SERVING_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR})
SET(PADDLE_SERVING_INSTALL_DIR ${CMAKE_BINARY_DIR}/output)
SET(CMAKE_INSTALL_RPATH "$ORIGIN" "${CMAKE_INSTALL_RPATH}")
include(system)
project(paddle-serving CXX C)
message(STATUS "CXX compiler: ${CMAKE_CXX_COMPILER}, version: "
"${CMAKE_CXX_COMPILER_ID} ${CMAKE_CXX_COMPILER_VERSION}")
message(STATUS "C compiler: ${CMAKE_C_COMPILER}, version: "
"${CMAKE_C_COMPILER_ID} ${CMAKE_C_COMPILER_VERSION}")
find_package(Git REQUIRED)
find_package(Threads REQUIRED)
find_package(CUDA QUIET)
include(simd)
SET(CMAKE_BUILD_TYPE "Debug")
CMAKE_BUILD_TYPE
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "RelWithDebInfo" CACHE STRING
"Choose the type of build, options are: Debug Release RelWithDebInfo MinSizeRel"
FORCE)
endif()
SET(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g2 -ggdb")
SET(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall")
set(THIRD_PARTY_PATH "${CMAKE_BINARY_DIR}/third_party" CACHE STRING
"A path setting third party libraries download & build directories.")
set(THIRD_PARTY_BUILD_TYPE Release)
option(WITH_AVX "Compile Paddle Serving with AVX intrinsics" OFF)
option(WITH_MKL "Compile Paddle Serving with MKL support." OFF)
option(WITH_GPU "Compile Paddle Serving with NVIDIA GPU" OFF)
option(WITH_LITE "Compile Paddle Serving with Paddle Lite Engine" OFF)
option(WITH_XPU "Compile Paddle Serving with Baidu Kunlun" OFF)
option(WITH_PYTHON "Compile Paddle Serving with Python" ON)
option(CLIENT "Compile Paddle Serving Client" OFF)
option(SERVER "Compile Paddle Serving Server" OFF)
option(APP "Compile Paddle Serving App package" OFF)
option(WITH_ELASTIC_CTR "Compile ELASITC-CTR solution" OFF)
option(PACK "Compile for whl" OFF)
option(WITH_TRT "Compile Paddle Serving with TRT" OFF)
option(PADDLE_ON_INFERENCE "Compile for encryption" ON)
option(WITH_OPENCV "Compile Paddle Serving with OPENCV" OFF)
option(WITH_ROCM "Compile Paddle Serving with ROCM" OFF)
option(WITH_ASCEND_CL "Compile PaddlePaddle with ASCEND CL" OFF)
option(WITH_JETSON "Compile PaddlePaddle with JETSON" OFF)
if(NOT DEFINED VERSION_TAG)
set(VERSION_TAG "0.0.0")
endif()
if (WITH_PYTHON)
message(STATUS "Compile Version Tag for wheel: ${VERSION_TAG}")
endif()
if (WITH_OPENCV)
SET(OPENCV_DIR "" CACHE PATH "Location of libraries")
if(NOT DEFINED OPENCV_DIR)
message(FATAL_ERROR "please set OPENCV_DIR with -DOPENCV_DIR=/path/opencv")
endif()
if (WIN32)
find_package(OpenCV REQUIRED PATHS ${OPENCV_DIR}/build/ NO_DEFAULT_PATH)
else ()
find_package(OpenCV REQUIRED PATHS ${OPENCV_DIR}/share/OpenCV NO_DEFAULT_PATH)
endif ()
include_directories(${OpenCV_INCLUDE_DIRS})
endif()
if (PADDLE_ON_INFERENCE)
add_definitions(-DPADDLE_ON_INFERENCE)
message(STATUS "Use PADDLE_ON_INFERENCE")
endif()
set(WITH_MKLML ${WITH_MKL})
if (NOT DEFINED WITH_MKLDNN)
if (WITH_MKL AND AVX2_FOUND)
set(WITH_MKLDNN ON)
else()
message(STATUS "Do not have AVX2 intrinsics and disabled MKL-DNN")
set(WITH_MKLDNN OFF)
endif()
endif()
if (SERVER OR CLIENT)
include(external/snappy)
include(external/leveldb)
include(external/zlib)
include(external/boost)
include(external/protobuf)
include(external/brpc)
include(external/gflags)
include(external/glog)
include(external/utf8proc)
if (WITH_PYTHON)
include(external/pybind11)
include(external/python)
endif()
include(generic)
include(flags)
endif()
if (APP)
include(external/zlib)
include(external/boost)
include(external/protobuf)
include(external/gflags)
include(external/glog)
include(external/pybind11)
include(external/python)
include(generic)
endif()
if (SERVER)
include(external/jsoncpp)
#include(external/rocksdb)
include(external/cudnn)
include(paddlepaddle)
include(external/prometheus)
endif()
message("paddle serving source dir: " ${PADDLE_SERVING_SOURCE_DIR})
include_directories(${PADDLE_SERVING_SOURCE_DIR})
include_directories(${PADDLE_SERVING_BINARY_DIR})
if(SERVER)
set(EXTERNAL_LIBS
jsoncpp
gflags
rocksdb
glog
protobuf
paddlepaddle
brpc)
endif()
set(EXTERNAL_LIBS
gflags
glog
protobuf
brpc
)
if(SERVER)
if(WITH_MKLML)
list(APPEND EXTERNAL_LIBS ${MKLML_IOMP_LIB})
endif()
if(WITH_MKLDNN)
list(APPEND EXTERNAL_LIBS ${MKLDNN_LIB})
endif()
list(APPEND EXTERNAL_LIBS paddlepaddle)
if(WITH_ROCM)
include(hip)
endif()
if(WITH_ASCEND_CL)
include(external/ascend)
list(APPEND EXTERNAL_LIBS ascend ascend_cl)
endif()endif()
add_subdirectory(core)
if(SERVER)
add_subdirectory(paddle_inference)
endif()
if (WITH_PYTHON)
add_subdirectory(python)
endif()
File: README_CN.md
(简体中文|English)
Documentation
Set up
This chapter guides you through the installation and deployment steps. It is strongly recommended to use Docker to deploy Paddle Serving. If you do not use docker, ignore the docker-related steps. Paddle Serving can be deployed on cloud servers using Kubernetes, running on many commonly hardwares such as ARM CPU, Intel CPU, Nvidia GPU, Kunlun XPU. The latest development kit of the develop branch is compiled and generated every day for developers to use.
- Install Paddle Serving using docker
- Build Paddle Serving from Source with Docker
- Install Paddle Serving on linux system
- Deploy Paddle Serving on Kubernetes(Chinese)
- Deploy Paddle Serving with Security gateway(Chinese)
- Deploy on more hardwares[ARM CPU、百度昆仑、华为昇腾、海光DCU、Jetson]
- Docker Images
- Download Wheel packages
Use
The first step is to call the model save interface to generate a model parameter configuration file (.prototxt), which will be used on the client and server. The second step, read the configuration and startup parameters and start the service. According to API documents and your case, the third step is to write client requests based on the SDK, and test the inference service.
- Quick Start
- Save a servable model
- Description of configuration and startup parameters
- Guide for RESTful/gRPC/bRPC APIs(Chinese)
- Infer on quantizative models
- Data format of classic models(Chinese)
- Prometheus(Chinese)
- C++ Serving(Chinese)
- Python Pipeline Overview(Chinese)
- Client SDK
- Large-scale sparse parameter server
Developers
For Paddle Serving developers, we provide extended documents such as custom OP, level of detail(LOD) processing.
Model Zoo
Paddle Serving works closely with the Paddle model suite, and implements a large number of service deployment examples, including image classification, object detection, language and text recognition, Chinese part of speech, sentiment analysis, content recommendation and other types of examples, for a total of 46 models.
For more model examples, read Model zoo
Community
If you want to communicate with developers and other users? Welcome to join us, join the community through the following methods below.
- WeChat scavenging
- QQ Group(Group No.:697765514)
Contribution
If you want to contribute code to Paddle Serving, please reference Contribution Guidelines
- Thanks to @loveululu for providing python API of Cube.
- Thanks to @EtachGu in updating run docker codes.
- Thanks to @BeyondYourself in complementing the gRPC tutorial, updating the FAQ doc and modifying the mdkir command
- Thanks to @mcl-stone in updating faster_rcnn benchmark
- Thanks to @cg82616424 in updating the unet benchmark modifying resize comment error
- Thanks to @cuicheng01 for providing 11 PaddleClas models
- Thanks to @Jiaqi Liu for supporting prediction for string list input
- Thanks to @Bin Lu for adding pp-shitu example
Feedback
For any feedback or to report a bug, please propose a GitHub Issue.
License
File: .pre-commit-config.yaml
repos:
- repo: https://github.com/Lucas-C/pre-commit-hooks.git
sha: v1.0.1
hooks:- id: remove-crlf
files: (?!.third_party)^.$ | (?!.book)^.$
- id: remove-crlf
- repo: https://github.com/PaddlePaddle/mirrors-yapf.git
sha: 0d79c0c469bab64f7229c9aca2b1186ef47f0e37
hooks:- id: yapf
files: (..(py|bzl)|BUILD|..BUILD|WORKSPACE)$
- id: yapf
- repo: https://github.com/pre-commit/pre-commit-hooks
sha: 5bf6c09bfa1297d3692cadd621ef95f1284e33c0
hooks:- id: check-added-large-files
- id: check-merge-conflict
- id: check-symlinks
- id: detect-private-key
files: (?!.third_party)^.$ | (?!.book)^.$ - id: end-of-file-fixer
- repo: local
hooks:- id: clang-format-with-version-check
name: clang-format
entry: bash ./tools/codestyle/clang_format.hook -i
language: system
files: .(c|cc|cxx|cpp|cu|h|hpp|hxx|proto)$
- id: clang-format-with-version-check
- repo: local
hooks:- id: cpplint-cpp-source
name: cpplint
entry: bash ./tools/codestyle/cpplint_pre_commit.hook
language: system
files: .(c|cc|cxx|cpp|cu|h|hpp|hxx)$
- id: cpplint-cpp-source
- repo: local
hooks:- id: pylint-doc-string
name: pylint
entry: bash ./tools/codestyle/pylint_pre_commit.hook
language: system
files: .(py)$
- id: pylint-doc-string
- repo: local
hooks:- id: copyright_checker
name: copyright_checker
entry: python ./tools/codestyle/copyright.hook
language: system
files: .(c|cc|cxx|cpp|cu|h|hpp|hxx|proto|py)$
exclude: (?!.third_party)^.$ | (?!.book)^.$
- id: copyright_checker
File: .travis.yml
language: generic
sudo: required
dist: trusty
os:
- linux
env:
- COMPILE_TYPE=CPU DOCKERFILE_CPU=$PWD/tools/Dockerfile.ci
services:
- docker
before_install:
- docker build -f ${DOCKERFILE_CPU} -t serving-img:${COMPILE_TYPE} .
install:
- if [ $COMPILE_TYPE == "CPU" ]; then docker run -it -v $PWD:/Serving serving-img:${COMPILE_TYPE} /bin/bash Serving/tools/serving_check_style.sh ; fi;
- docker run -it -v $PWD:/Serving serving-img:${COMPILE_TYPE} /bin/bash Serving/tools/serving_build.sh $COMPILE_TYPE
File: core/CMakeLists.txt
Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
if(SERVER)
add_subdirectory(cube)
#add_subdirectory(kvdb)
endif()
if (CLIENT OR SERVER)
add_subdirectory(configure)
add_subdirectory(pdcodegen)
add_subdirectory(sdk-cpp)
endif()
if (APP)
add_subdirectory(configure)
add_subdirectory(preprocess)
endif()
if(CLIENT)
add_subdirectory(general-client)
endif()
if (SERVER)
add_subdirectory(predictor)
add_subdirectory(general-server)
endif()
if (CLIENT OR SERVER)
add_subdirectory(util)
endif()
File: core/configure/CMakeLists.txt
if (SERVER OR CLIENT)
LIST(APPEND protofiles
${CMAKE_CURRENT_LIST_DIR}/proto/server_configure.proto
${CMAKE_CURRENT_LIST_DIR}/proto/sdk_configure.proto
${CMAKE_CURRENT_LIST_DIR}/proto/inferencer_configure.proto
${CMAKE_CURRENT_LIST_DIR}/proto/general_model_config.proto
)
PROTOBUF_GENERATE_CPP(configure_proto_srcs configure_proto_hdrs ${protofiles})
list(APPEND configure_srcs ${configure_proto_srcs})
list(APPEND configure_srcs ${CMAKE_CURRENT_LIST_DIR}/src/configure_parser.cpp)
add_library(configure ${configure_srcs})
add_dependencies(configure brpc)
install(TARGETS configure
ARCHIVE DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/lib
)
install(FILES ${CMAKE_CURRENT_LIST_DIR}/include/configure_parser.h
DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/include/configure/include)
FILE(GLOB inc ${CMAKE_CURRENT_BINARY_DIR}/*.pb.h)
install(FILES ${inc}
DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/include/configure)
endif()
if (WITH_PYTHON)
py_proto_compile(general_model_config_py_proto SRCS proto/general_model_config.proto)
add_custom_target(general_model_config_py_proto_init ALL COMMAND ${CMAKE_COMMAND} -E touch init.py)
add_dependencies(general_model_config_py_proto general_model_config_py_proto_init)
py_grpc_proto_compile(general_model_service_py_proto SRCS proto/general_model_service.proto)
add_custom_target(general_model_service_py_proto_init ALL COMMAND ${CMAKE_COMMAND} -E touch init.py)
add_dependencies(general_model_service_py_proto general_model_service_py_proto_init)
if (CLIENT)
py_proto_compile(sdk_configure_py_proto SRCS proto/sdk_configure.proto)
add_custom_target(sdk_configure_py_proto_init ALL COMMAND ${CMAKE_COMMAND} -E touch init.py)
add_dependencies(sdk_configure_py_proto sdk_configure_py_proto_init)
add_custom_command(TARGET sdk_configure_py_proto POST_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory ${PADDLE_SERVING_BINARY_DIR}/python/paddle_serving_client/proto
COMMAND cp -f *.py ${PADDLE_SERVING_BINARY_DIR}/python/paddle_serving_client/proto
COMMENT "Copy generated python proto into directory paddle_serving_client/proto."
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
add_custom_command(TARGET general_model_config_py_proto POST_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory ${PADDLE_SERVING_BINARY_DIR}/python/paddle_serving_client/proto
COMMAND cp -f *.py ${PADDLE_SERVING_BINARY_DIR}/python/paddle_serving_client/proto
COMMENT "Copy generated general_model_config proto file into directory paddle_serving_client/proto."
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
add_custom_command(TARGET general_model_service_py_proto POST_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory ${PADDLE_SERVING_BINARY_DIR}/python/paddle_serving_client/proto
COMMAND cp -f *.py ${PADDLE_SERVING_BINARY_DIR}/python/paddle_serving_client/proto
COMMENT "Copy generated general_model_service proto file into directory paddle_serving_client/proto."
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})endif()
if (APP)
add_custom_command(TARGET general_model_config_py_proto POST_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory ${PADDLE_SERVING_BINARY_DIR}/python/paddle_serving_app/proto
COMMAND cp -f *.py ${PADDLE_SERVING_BINARY_DIR}/python/paddle_serving_app/proto
COMMENT "Copy generated general_model_config proto file into directory paddle_serving_app/proto."
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
endif()
if (SERVER)
py_proto_compile(server_config_py_proto SRCS proto/server_configure.proto)
add_custom_target(server_config_py_proto_init ALL COMMAND ${CMAKE_COMMAND} -E touch init.py)
add_dependencies(server_config_py_proto server_config_py_proto_init)
add_custom_command(TARGET server_config_py_proto POST_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory ${PADDLE_SERVING_BINARY_DIR}/python/paddle_serving_server/proto
COMMAND cp -f *.py ${PADDLE_SERVING_BINARY_DIR}/python/paddle_serving_server/proto
COMMENT "Copy generated python proto into directory paddle_serving_server/proto."
WORKING_DIRECTORY ${CMAKE_CURRENT_BINRARY_DIR})
add_custom_command(TARGET general_model_config_py_proto POST_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory ${PADDLE_SERVING_BINARY_DIR}/python/paddle_serving_server/proto
COMMAND cp -f *.py ${PADDLE_SERVING_BINARY_DIR}/python/paddle_serving_server/proto
COMMENT "Copy generated general_model_config proto file into directory paddle_serving_server/proto."
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
add_custom_command(TARGET general_model_service_py_proto POST_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory ${PADDLE_SERVING_BINARY_DIR}/python/paddle_serving_server/proto
COMMAND cp -f *.py ${PADDLE_SERVING_BINARY_DIR}/python/paddle_serving_server/proto
COMMENT "Copy generated general_model_service proto file into directory paddle_serving_server/proto."
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})endif()
endif()
File: core/cube/CMakeLists.txt
Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
add_subdirectory(cube-server)
add_subdirectory(cube-api)
add_subdirectory(cube-builder)
add_subdirectory(cube-transfer)
add_subdirectory(cube-agent)
File: core/cube/cube-agent/CMakeLists.txt
Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
project(cube-agent Go)
include(cmake/golang.cmake)
ExternalGoProject_Add(agent-docopt-go github.com/docopt/docopt-go)
ExternalGoProject_Add(agent-logex github.com/Badangel/logex)
ExternalGoProject_Add(agent-pipeline github.com/Badangel/pipeline)
add_subdirectory(src)
File: core/cube/cube-agent/src/CMakeLists.txt
Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
set(SOURCE_FILE cube-agent.go)
add_go_executable(cube-agent ${SOURCE_FILE})
add_dependencies(cube-agent agent-docopt-go)
add_dependencies(cube-agent agent-logex)
add_dependencies(cube-agent agent-pipeline)
File: core/cube/cube-api/CMakeLists.txt
Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
protobuf_generate_cpp(PROTO_SRC PROTO_HEADER idl/cube.proto idl/control.proto)
include PROTO_HEADER
include_directories(${CMAKE_CURRENT_BINARY_DIR}/core)
if(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
include(CheckFunctionExists)
CHECK_FUNCTION_EXISTS(clock_gettime HAVE_CLOCK_GETTIME)
if(NOT HAVE_CLOCK_GETTIME)
set(DEFINE_CLOCK_GETTIME "-DNO_CLOCK_GETTIME_IN_MAC")
endif()
endif()
set(CMAKE_CXX_FLAGS "${CMAKE_CPP_FLAGS} -DNDEBUG -O2 -D__const__= -pipe -W -Wall -Wno-unused-parameter -fPIC -fno-omit-frame-pointer")
if(CMAKE_VERSION VERSION_LESS "3.1.3")
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
endif()
if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
endif()
else()
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
endif()
add_executable(cube-cli src/cube_cli.cpp src/cube_api.cpp src/meta.cpp
${PROTO_SRC} ${PROTO_HEADER})
add_library(cube-api STATIC src/cube_api.cpp src/meta.cpp
${PROTO_SRC} ${PROTO_HEADER})
set(DYNAMIC_LIB
gflags
protobuf
leveldb
-lssl
-lcrypto
)
if(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
set(DYNAMIC_LIB ${DYNAMIC_LIB}
"-framework CoreFoundation"
"-framework CoreGraphics"
"-framework CoreData"
"-framework CoreText"
"-framework Security"
"-framework Foundation"
"-Wl,-U,_MallocExtension_ReleaseFreeMemory"
"-Wl,-U,_ProfilerStart"
"-Wl,-U,_ProfilerStop")
endif()
target_link_libraries(cube-cli brpc ${DYNAMIC_LIB} -lpthread -ldl -lz)
target_link_libraries(cube-api ${DYNAMIC_LIB} brpc -lpthread -ldl -lz)
install
install(TARGETS cube-api
ARCHIVE DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/lib
)
install(DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/include
DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/include/cube-api)
FILE(GLOB inc ${CMAKE_CURRENT_BINARY_DIR}/*.pb.h)
install(FILES ${inc}
DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/include/cube-api)
File: core/cube/cube-api/go-api/input.json
{"keys": [0,1,2,3,4,5,6,7]}
{"keys": [1]}
File: core/cube/cube-api/python-api/input.json
{"keys": [0,1,2,3,4,5,6,7]}
{"keys": [1]}
File: core/cube/cube-api/python-api/ptyhon_api.md
cube python api说明文档
参考大规模稀疏参数服务Cube的部署和使用文档进行cube的部署。
使用python api,可替代上述文档中第3节预测服务的部署、使用
配置说明
conf/cube.conf 以json格式,设置各个分片cube server的ip以及port,shard与分片数一致,示例:
[{
"dict_name": "test",
"shard": 2,
"nodes": [{
"ip": "127.0.0.1",
"port": 8731
},{
"ip": "127.0.0.1",
"port": 8730
}]
}]数据格式
{"keys": [0,1,2,3,4,5,6,7]}
{"keys": [1]}支持批量查询,每次查询一行
使用
cd ./python-api
python3 demo.py conf/cube.conf test input.json result.jsonFile: core/cube/cube-api/python-api/result.json
{"values": [{"status": 4294967295, "value": ""}, {"status": 4294967295, "value": ""}, {"status": 4294967295, "value": ""}, {"status": 4294967295, "value": ""}, {"status": 4294967295, "value": ""}, {"status": 4294967295, "value": ""}, {"status": 4294967295, "value": ""}, {"status": 4294967295, "value": ""}]}
{"values": [{"status": 4294967295, "value": ""}]}
File: core/cube/cube-builder/CMakeLists.txt
Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
set(CMAKE_CXX_STANDARD 11)
add_compile_options(-std=c++11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include_directories(SYSTEM ${CMAKE_CURRENT_LIST_DIR}/include)
include_directories(SYSTEM ${CMAKE_CURRENT_BINARY_DIR}/../)
add_executable(cube-builder src/main.cpp include/cube-builder/util.h src/util.cpp src/builder_job.cpp include/cube-builder/builder_job.h include/cube-builder/define.h src/seqfile_reader.cpp include/cube-builder/seqfile_reader.h include/cube-builder/raw_reader.h include/cube-builder/vtext.h src/crovl_builder_increment.cpp include/cube-builder/crovl_builder_increment.h src/curl_simple.cpp include/cube-builder/curl_simple.h)
add_dependencies(cube-builder jsoncpp boost brpc)
set(DYNAMIC_LIB
gflags
jsoncpp
brpc
-lcurl
-lssl
-lcrypto
${CURL_LIB}
)
target_link_libraries(cube-builder ${DYNAMIC_LIB})
install
install(TARGETS cube-builder RUNTIME DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/bin)
install(FILES ${CMAKE_CURRENT_LIST_DIR}/tool/kvtool.py DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/tool)
install(FILES ${CMAKE_CURRENT_LIST_DIR}/tool/kv_to_seqfile.py DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/tool)
install(DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/tool/source DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/tool)
File: core/cube/cube-builder/tool/source/file.txt
1:1
2:2
3:3
4:4
5:5
7:7
8:8
9:9
10:10 11 12
11:this is eleven
12:value can string
1676869128226002114:48241 37064 91 -539 114 51 -122 269 229 -134 -282
1657749292782759014:167 40 98 27 117 10 -29 15 74 67 -54
1657618343175325789:1089 149 -28 110 -102 28 31 -11 6 62 -8
1676918088588087334:5 -27 29 27 -6 -5 -12 -2 -4 -24
1657827627464525106:236 229 -8 -42 124 -226 -307 179 40 -101 -162
1657635389944349858:2149 1114 -33 -74 94 83 -53 -61 -104 -120 11
1657837006931146296:28 16 -6 2 -15 -30 4 27 -24 13 34
File: core/cube/cube-server/CMakeLists.txt
Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
include_directories(SYSTEM ${CMAKE_CURRENT_LIST_DIR}/include)
include_directories(SYSTEM ${CMAKE_CURRENT_BINARY_DIR}/../)
protobuf_generate_cpp(PROTO_SRC PROTO_HEADER proto/cube.proto proto/control.proto)
include PROTO_HEADER
include_directories(${CMAKE_CURRENT_BINARY_DIR})
set(CMAKE_CXX_FLAGS "${CMAKE_CPP_FLAGS} -DNDEBUG -O2 -D__const__= -pipe -W -Wall -Wno-unused-parameter -fPIC -fno-omit-frame-pointer")
if(CMAKE_VERSION VERSION_LESS "3.1.3")
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
endif()
if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
endif()
else()
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
endif()
set(SRC_LIST src/server.cpp
src/cube_bvar.cpp
src/dict.cpp
src/dict_set.cpp
src/recycle.cpp
src/framework.cpp
src/control.cpp
src/server.cpp)
add_executable(cube ${SRC_LIST} src/main.cpp
${PROTO_SRC} ${PROTO_HEADER})
set(DYNAMIC_LIB
protobuf
leveldb
-lssl
-lcrypto
)
if(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
set(DYNAMIC_LIB ${DYNAMIC_LIB}
"-framework CoreFoundation"
"-framework CoreGraphics"
"-framework CoreData"
"-framework CoreText"
"-framework Security"
"-framework Foundation"
"-Wl,-U,_MallocExtension_ReleaseFreeMemory"
"-Wl,-U,_ProfilerStart"
"-Wl,-U,_ProfilerStop")
endif()
target_link_libraries(cube brpc ${DYNAMIC_LIB} -lpthread -ldl -lz)
#add_executable(cube_test ${SRC_LIST} test/cube_test.cpp
${PROTO_SRC} ${PROTO_HEADER})
#target_link_libraries(cube_test brpc ${DYNAMIC_LIB} gtest -lpthread -ldl -lz)
install
install(TARGETS cube
RUNTIME DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/bin
)
install(DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/conf DESTINATION
${PADDLE_SERVING_INSTALL_DIR})
File: core/cube/cube-transfer/CMakeLists.txt
Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
project(cube-transfer Go)
include(cmake/golang.cmake)
ExternalGoProject_Add(transfer-rfw github.com/mipearson/rfw)
ExternalGoProject_Add(transfer-docopt-go github.com/docopt/docopt-go)
ExternalGoProject_Add(transfer-logex github.com/Badangel/logex)
add_subdirectory(src)
install(DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/conf DESTINATION ${PADDLE_SERVING_INSTALL_DIR})
File: core/cube/cube-transfer/src/CMakeLists.txt
Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
set(SOURCE_FILE cube-transfer.go)
add_go_executable(cube-transfer ${SOURCE_FILE})
add_dependencies(cube-transfer transfer-docopt-go)
add_dependencies(cube-transfer transfer-rfw)
add_dependencies(cube-transfer transfer-logex)
File: core/cube/doc/performance.md
Cube Server 社区版本性能报告
机器配置
Intel(R) Xeon(R) CPU E5-2650 v4 @ 2.20GHz
测试方法
请参考压测文档
测试数据
100w条样例kv 数据。 key为uint_64类型,单条value长度 40 Byte (一般实际场景对应一个10维特征向量)。
单Key高qps访问场景
一般来说实际预估服务生产环境下,单key访问场景较少,不过单机qps依然是一个比较重要的性能指标,故在下表提供了不同qps下单机Cube server性能指标。
| qps | 10w | 50w | 100w |
|---|---|---|---|
| kps | 10w | 50w | 100w |
| cpu(top) | 6.5% | 38.3% | 71.4% |
| client端延迟 | avg 196 us50% 160 us70% 188 us90% 292 us95% 419 us97% 547 us99% 835 us99.9% 1556 us99.99% 1779 us | avg 563 us50% 342 us70% 502 us90% 1063 us95% 1703 us97% 2399 us 99% 4036 us99.9% 7195 us99.99% 7340 us | avg 4234 us50% 3120 us70% 5459 us90% 10657 us95% 14074 us97% 16215 us 99% 19434 us99.9% 29398 us99.99% 33921 us |
高kps场景
生产环境下,预估服务更多的会以batch形式访问cube server,这类情况kps相对qps能更准确的判断服务性能。我们以单次100key为例,给出不同kps下cube server的相关性能指标。
| qps | 2w | 10w | 20w |
|---|---|---|---|
| kps | 200w | 1000w | 2000w |
| cpu(top) | 3.5% | 17.8% | 37.6% |
| client端延迟 | avg 375 us50% 346 us70% 390 us90% 498 us95% 582 us97% 648 us99% 908 us99.9% 1623 us99.99% 3312 us | avg 1141 us50% 900 us70% 1237 us90% 2028 us95% 2662 us97% 3173 us99% 4614 us 99.9% 6786 us99.99% 6273 us | avg 1940 us50% 1299 us70% 1876 us90% 3629 us95% 5535 us97% 7365 us99% 10529 us99.9% 14060 us99.99% 16028 us |
分布式场景客户端延迟
在batch查询场景下,单次batch查询耗时是业务方(特别是在线预估服务)非常关心的敏感指标。在分布式场景下,单次batch查询往往要并发请求下游所有分片server,此时batch查询耗时取决于最慢的分片请求。我们在下文给出了一个典型分布式场景下的batch查询耗时。
测试条件:
cube分片数:10
client机器ping下游server机器约0.06ms
| batch size | 100 | 500 | 1000 |
|---|---|---|---|
| qps | 100 | 100 | 100 |
| kps | 1w | 5w | 10w |
| client端延迟 | avg 324 us80% 346 us99% 1190 us99.9% 3662 us99.99% 9392 us | avg 466 us80% 488 us99% 1492 us99.9% 4122 us99.99% 10612 us | avg 675 us80% 691 us99% 2101 us99.9% 5169 us99.99% 14867 us |
结语
上述表格主要阐述了cube server单机性能,在生产环境下,对于更高的kps(qps)压力我们可以方便地通过增加副本的方式来增强集群负载能力。 在模型大小超过单机内存限制时,我们亦可通过部署多数据分片的分布式集群来提供服务。
整体来说,cube性能能够满足当前业界各类预估服务的kv访问需求。
PS
本文所列性能均为cube原始代码版本性能,如果根据实际情情况做适当调优:如链入tcmalloc or jemalloc、 进行numa绑定 以及 打开编译优化参数等等,都有可能进一步明显提升cube server的性能表现。
File: core/cube/doc/press.md
[Binary file]
File: core/general-client/README.md
install
pip install paddle-serving-client
quick-start example
# train text classification problem with paddle
# save serving modelfrom serving_client import serving_io
serving_io.save_serving_model()
# load serving model configuration and start service# load serving model configuration in client and do predictiondesign
paddle sering as remote executor run
high level features
C++ client
File: core/general-client/CMakeLists.txt
if(CLIENT)
add_subdirectory(pybind11)
pybind11_add_module(serving_client src/general_model.cpp src/pybind_general_model.cpp)
target_link_libraries(serving_client PRIVATE -Wl,--whole-archive utils sdk-cpp pybind python -Wl,--no-whole-archive -lpthread -lcrypto -lm -lrt -lssl -ldl -lz -Wl,-rpath,'$ORIGIN'/lib)
endif()
if(CLIENT)
FILE(GLOB client_srcs include/*.h src/client.cpp src/brpc_client.cpp)
add_library(client ${client_srcs})
add_dependencies(client utils sdk-cpp)
target_link_libraries(client utils sdk-cpp)
endif()
if(CLIENT)
include_directories(SYSTEM ${CMAKE_CURRENT_LIST_DIR}/../../)
add_executable(simple_client example/simple_client.cpp)
add_dependencies(simple_client utils sdk-cpp client)
target_link_libraries(simple_client -Wl,--whole-archive
-Wl,--no-whole-archive -Wl,--start-group -lpthread -lcrypto -lm -lrt -lssl -ldl -lz -Wl,-rpath,'$ORIGIN'/lib)
target_link_libraries(simple_client utils)
target_link_libraries(simple_client sdk-cpp)
target_link_libraries(simple_client client)
endif()
File: core/general-client/README_CN.md
用于Paddle Serving的C++客户端
(简体中文|English)
请求BRPC-Server
服务端启动
以fit_a_line模型为例,服务端启动与常规BRPC-Server端启动命令一样。
cd ../../examples/C++/fit_a_line
sh get_data.sh
python -m paddle_serving_server.serve --model uci_housing_model --thread 10 --port 9393客户端预测
客户端目前支持BRPC
目前已经实现了BRPC的封装函数,详见brpc_client.cpp
./simple_client --client_conf="uci_housing_client/serving_client_conf.prototxt" --server_port="127.0.0.1:9393" --test_type="brpc" --sample_type="fit_a_line"更多示例详见simple_client.cpp
| Argument | Type | Default | Description |
|---|---|---|---|
client_conf |
str | "serving_client_conf.prototxt" |
Path of client conf |
server_port |
str | "127.0.0.1:9393" |
Exposed ip:port of server |
test_type |
str | "brpc" |
Mode of request "brpc" |
sample_type |
str | "fit_a_line" |
Type of sample include "fit_a_line,bert" |
File: core/general-server/CMakeLists.txt
include_directories(SYSTEM ${CMAKE_CURRENT_LIST_DIR}/../../)
include(op/CMakeLists.txt)
include(proto/CMakeLists.txt)
add_executable(serving ${serving_srcs})
add_dependencies(serving pdcodegen paddle_inference_engine pdserving paddle_inference cube-api utils utf8proc)
if (WITH_GPU)
add_dependencies(serving paddle_inference_engine)
endif()
if (WITH_LITE)
add_dependencies(serving paddle_inference_engine)
endif()
target_include_directories(serving PUBLIC
${CMAKE_CURRENT_BINARY_DIR}/../../core/predictor
)
include_directories(${CUDNN_ROOT}/include/)
target_link_libraries(serving -Wl,--whole-archive paddle_inference_engine
-Wl,--no-whole-archive)
if(WITH_OPENCV)
target_link_libraries(serving ${OpenCV_LIBS})
endif()
target_link_libraries(serving paddle_inference ${paddle_depend_libs})
target_link_libraries(serving brpc)
target_link_libraries(serving protobuf)
target_link_libraries(serving pdserving)
target_link_libraries(serving cube-api)
target_link_libraries(serving utils)
target_link_libraries(serving utf8proc)
target_link_libraries(serving prometheus ${prometheus_libs})
if(WITH_ASCEND_CL AND NOT WITH_LITE)
target_link_libraries(serving ascendcl acl_op_compiler)
endif()
if(WITH_GPU)
target_link_libraries(serving ${CUDA_LIBRARIES})
endif()
if(WITH_MKL OR WITH_GPU)
if (WITH_JETSON)
target_link_libraries(serving openblas -lpthread -lcrypto -lm -lrt -lssl -ldl -lz -lbz2)
elseif (WITH_TRT)
target_link_libraries(serving -liomp5 -lmklml_intel -lpthread -lcrypto -lm -lrt -lssl -ldl -lz -lbz2 -ldnnl)
else()
target_link_libraries(serving -liomp5 -lmklml_intel -lmkldnn -lpthread -lcrypto -lm -lrt -lssl -ldl -lz -lbz2)
endif()
else()
target_link_libraries(serving openblas -lpthread -lcrypto -lm -lrt -lssl -ldl -lz -lbz2)
endif()
install(TARGETS serving
RUNTIME DESTINATION
${PADDLE_SERVING_INSTALL_DIR}/demo/serving/bin)
FILE(GLOB inc ${CMAKE_CURRENT_BINARY_DIR}/*.pb.h)
install(FILES ${inc}
DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/include/serving)
if (${WITH_MKL})
install(FILES
${CMAKE_BINARY_DIR}/third_party/install/Paddle/third_party/install/mklml/lib/libmklml_intel.so
${CMAKE_BINARY_DIR}/third_party/install/Paddle/third_party/install/mklml/lib/libiomp5.so
${CMAKE_BINARY_DIR}/third_party/install/Paddle/third_party/install/mkldnn/lib/libmkldnn.so.0
${CMAKE_BINARY_DIR}/third_party/install/Paddle/third_party/install/mkldnn/lib/libdnnl.so.1
DESTINATION
${PADDLE_SERVING_INSTALL_DIR}/demo/serving/bin)
endif()
if (WITH_ROCM)
target_link_libraries(serving ${ROCM_HIPRTC_LIB})
endif()
File: core/general-server/op/CMakeLists.txt
FILE(GLOB op_srcs ${CMAKE_CURRENT_LIST_DIR}/.cpp ${CMAKE_CURRENT_LIST_DIR}/../../predictor/tools/quant.cpp)
if(WITH_OPENCV)
FILE(GLOB ocrtools_srcs ${CMAKE_CURRENT_LIST_DIR}/../../predictor/tools/ocrtools/.cpp)
FILE(GLOB ppshitu_tools_srcs ${CMAKE_CURRENT_LIST_DIR}/../../predictor/tools/pp_shitu_tools/*.cpp)
LIST(APPEND op_srcs ${ppshitu_tools_srcs})
LIST(APPEND op_srcs ${ocrtools_srcs})
else()
LIST(APPEND EXCLUDE_LIST "general_detection_op.cpp")
LIST(APPEND EXCLUDE_LIST "general_picodet_op.cpp")
LIST(APPEND EXCLUDE_LIST "general_feature_extract_op.cpp")
foreach (TMP_PATH ${op_srcs})
foreach (EXCLUDE_DIR ${EXCLUDE_LIST})
string (FIND ${TMP_PATH} ${EXCLUDE_DIR} EXCLUDE_DIR_FOUND)
if (NOT ${EXCLUDE_DIR_FOUND} EQUAL -1)
list (REMOVE_ITEM op_srcs ${TMP_PATH})
break()
endif ()
endforeach(EXCLUDE_DIR)
endforeach(TMP_PATH)
endif()
LIST(APPEND serving_srcs ${op_srcs})
File: core/general-server/proto/CMakeLists.txt
LIST(APPEND protofiles
${CMAKE_CURRENT_LIST_DIR}/load_general_model_service.proto
${CMAKE_CURRENT_LIST_DIR}/general_model_service.proto
)
PROTOBUF_GENERATE_SERVING_CPP(TRUE PROTO_SRCS PROTO_HDRS ${protofiles})
LIST(APPEND serving_srcs ${PROTO_SRCS})
File: core/kvdb/CMakeLists.txt
include_directories(SYSTEM ${CMAKE_CURRENT_LIST_DIR}/include)
set(SRC_LIST ${CMAKE_CURRENT_LIST_DIR}/src/rockskvdb_impl.cpp
${CMAKE_CURRENT_LIST_DIR}/src/param_dict_mgr_impl.cpp
${CMAKE_CURRENT_LIST_DIR}/src/mock_param_dict_impl.cpp
${CMAKE_CURRENT_LIST_DIR}/src/paddle_rocksdb.cpp)
add_library(kvdb ${SRC_LIST})
add_dependencies(kvdb rocksdb)
install(TARGETS kvdb ARCHIVE DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/lib/)
set(SRC_LIST2 ${CMAKE_CURRENT_LIST_DIR}/src/rockskvdb_impl.cpp
${CMAKE_CURRENT_LIST_DIR}/src/param_dict_mgr_impl.cpp
${CMAKE_CURRENT_LIST_DIR}/src/mock_param_dict_impl.cpp
${CMAKE_CURRENT_LIST_DIR}/src/paddle_rocksdb.cpp)
file(GLOB kvdb_headers "${CMAKE_CURRENT_LIST_DIR}/include/kvdb/*.h")
install(FILES ${kvdb_headers} DESTINATION
${PADDLE_SERVING_INSTALL_DIR}/include/kvdb/)
File: core/pdcodegen/CMakeLists.txt
include(plugin/CMakeLists.txt)
include(src/CMakeLists.txt)
PROTOBUF_GENERATE_CPP(pdcodegen_proto_srcs pdcodegen_proto_hdrs
${CMAKE_SOURCE_DIR}/core/predictor/proto/pds_option.proto)
LIST(APPEND pdcodegen_srcs ${pdcodegen_proto_srcs})
add_executable(pdcodegen ${pdcodegen_srcs})
add_dependencies(pdcodegen boost protobuf)
target_link_libraries(pdcodegen protobuf ${PROTOBUF_PROTOC_LIBRARY})
install
install(TARGETS pdcodegen
RUNTIME DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/bin
ARCHIVE DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/lib
LIBRARY DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/so
)
File: core/pdcodegen/plugin/CMakeLists.txt
FILE(GLOB plugin_srcs ${CMAKE_CURRENT_LIST_DIR}/*.cc)
LIST(APPEND pdcodegen_srcs ${plugin_srcs})
File: core/pdcodegen/src/CMakeLists.txt
LIST(APPEND pdcodegen_srcs ${CMAKE_CURRENT_LIST_DIR}/pdcodegen.cpp)
File: core/predictor/CMakeLists.txt
include(proto/CMakeLists.txt)
include(common/CMakeLists.txt)
include(op/CMakeLists.txt)
include(mempool/CMakeLists.txt)
include(framework/CMakeLists.txt)
include(tools/CMakeLists.txt)
include(src/CMakeLists.txt)
add_definitions(-D__STDC_FORMAT_MACROS)
add_library(pdserving ${pdserving_srcs})
set_source_files_properties(
${pdserving_srcs}
PROPERTIES
COMPILE_FLAGS "-Wno-strict-aliasing -Wno-unused-variable -Wno-non-virtual-dtor -Wno-error=non-virtual-dtor -Wno-error=delete-non-virtual-dtor")
add_dependencies(pdserving protobuf boost brpc leveldb pdcodegen configure extern_paddle paddle_inference)
if (WITH_TRT)
add_definitions(-DWITH_TRT)
endif()
target_link_libraries(pdserving
brpc protobuf boost leveldb configure -lpthread -lcrypto -lm -lrt -lssl -ldl -lz paddle_inference ${paddle_depend_libs} prometheus ${prometheus_libs})
install
install(TARGETS pdserving
RUNTIME DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/bin
ARCHIVE DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/lib
LIBRARY DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/so
)
FILE(GLOB inc_common ${CMAKE_CURRENT_LIST_DIR}/common/*.h)
install(FILES ${inc_common}
DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/include/core/predictor/common)
FILE(GLOB inc_framework ${CMAKE_CURRENT_LIST_DIR}/framework/*.h)
install(FILES ${inc_framework}
DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/include/core/predictor/framework)
install(FILES ${CMAKE_CURRENT_LIST_DIR}/mempool/mempool.h
DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/include/core/predictor/mempool)
install(FILES ${CMAKE_CURRENT_LIST_DIR}/op/op.h
DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/include/core/predictor/op)
File: core/predictor/common/CMakeLists.txt
FILE(GLOB common_srcs ${CMAKE_CURRENT_LIST_DIR}/constant.cpp)
LIST(APPEND pdserving_srcs ${common_srcs})
File: core/predictor/framework/CMakeLists.txt
FILE(GLOB framework_srcs ${CMAKE_CURRENT_LIST_DIR}/*.cpp ${CMAKE_CURRENT_LIST_DIR}/../../cube/cube-builder/src/seqfile_reader.cpp)
LIST(APPEND pdserving_srcs ${framework_srcs})
LIST(APPEND pclient_srcs ${framework_srcs})
File: core/predictor/mempool/CMakeLists.txt
FILE(GLOB mempool_srcs ${CMAKE_CURRENT_LIST_DIR}/*.cpp)
LIST(APPEND pdserving_srcs ${mempool_srcs})
File: core/predictor/op/CMakeLists.txt
FILE(GLOB op_srcs ${CMAKE_CURRENT_LIST_DIR}/*.cpp)
LIST(APPEND pdserving_srcs ${op_srcs})
File: core/predictor/proto/CMakeLists.txt
PROTOBUF_GENERATE_CPP(pdcodegen_proto_srcs pdcodegen_proto_hdrs
${CMAKE_CURRENT_LIST_DIR}/pds_option.proto)
LIST(APPEND pdserving_srcs ${pdcodegen_proto_srcs})
LIST(APPEND protofiles
${CMAKE_CURRENT_LIST_DIR}/./builtin_format.proto
${CMAKE_CURRENT_LIST_DIR}/./msg_data.proto
${CMAKE_CURRENT_LIST_DIR}/./xrecord_format.proto
${CMAKE_CURRENT_LIST_DIR}/./framework.proto
)
PROTOBUF_GENERATE_SERVING_CPP(TRUE PROTO_SRCS PROTO_HDRS ${protofiles})
LIST(APPEND pdserving_srcs ${PROTO_SRCS} ${pdcodegen_proto_srcs})
File: core/predictor/src/CMakeLists.txt
LIST(APPEND pdserving_srcs ${CMAKE_CURRENT_LIST_DIR}/pdserving.cpp)
File: core/predictor/tools/CMakeLists.txt
set(seq_gen_src ${CMAKE_CURRENT_LIST_DIR}/seq_generator.cpp ${CMAKE_CURRENT_LIST_DIR}/seq_file.cpp ${CMAKE_CURRENT_LIST_DIR}/quant.cpp)
LIST(APPEND seq_gen_src ${PROTO_SRCS})
add_executable(seq_generator ${seq_gen_src})
target_link_libraries(seq_generator protobuf -lpthread)
set(seq_reader_src ${CMAKE_CURRENT_LIST_DIR}/seq_reader.cpp ${CMAKE_CURRENT_LIST_DIR}/../../cube/cube-builder/src/seqfile_reader.cpp)
add_executable(seq_reader ${seq_reader_src})
add_dependencies(seq_reader brpc)
install(TARGETS seq_reader
RUNTIME DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/bin
ARCHIVE DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/lib
LIBRARY DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/so
)
install(TARGETS seq_reader RUNTIME DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/tool)
install(TARGETS seq_generator RUNTIME DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/tool)
File: core/preprocess/CMakeLists.txt
if(NOT WITH_GPU)
message("GPU preprocess will not be compiled.")
return()
endif()
message(STATUS "CUDA detected: " ${CUDA_VERSION})
if (${CUDA_VERSION} LESS 10.0)
message("CUDA version should be 10.0.")
return()
elseif (${CUDA_VERSION} LESS 10.1) # CUDA 10.0
add_subdirectory(hwvideoframe)
endif()
File: core/preprocess/hwvideoframe/README.md
hwvideoframe
Hwvideoframe is a CV preprocessing library based on cuda. The project uses GPU for image preprocessing operations. It speeds up the processing speed while increasing the utilization rate of the GPU.
Preprocess API
Hwvideoframe provides a variety of data preprocessing methods for photo preprocess:
class Image2Gpubuffer
__call__(img)- img(np.array):Image data.
class Gpubuffer2Image
__call__(img)- img(np.array):Image data.
class Div
__init__(value)- value(float):Constant value to be divided.
__call__(img)- img(np.array):Image data.
class Sub
__init__(subtractor)- subtractor(list/float):Three 32-bit floating point channel image subtract constant. When the input is a list type, length of list must be three.
__call__(img)- img(np.array):Image data in (C,H,W) channels.
class Normalize
__init__(mean,std)- mean(list):Mean. Length of list must be three.
- std(list):Variance. Length of list must be three.
__call__(img)- img(np.array):Image data in (C,H,W) channels.
class CenterCrop
__init__(size)- size(int):Crops the given Image at the center while the size must not bigger than any inputs' height and width.
__call__(img)- img(np.array):Image data in (C,H,W) channels.
class Resize
__init__(size, max_size=2147483647, interpolation=None)- size(list/int):The expected image size, when the input is a list type, it needs to contain the expected length and width. When the input is int type, the short side will be set to the length of size, and the long side will be scaled proportionally.
__call__(img)- img(numpy array):Image data in (C,H,W) channels.
Quick start
After compiling from code,this project will be stored in reader。
How to Test
Test file:Serving/python/paddle_serving_app/reader/test_preprocess.py
File: core/preprocess/hwvideoframe/CMakeLists.txt
cmake_minimum_required(VERSION 3.2)
project(gpupreprocess)
include(cuda)
include(configure)
#C flags
set(CMAKE_C_FLAGS " -g -pipe -W -Wall -fPIC")
#C++ flags.
set(CMAKE_CXX_FLAGS " -g -pipe -W -Wall -fPIC -std=c++11")
add_subdirectory(cuda)
set(PYTHON_SO {PYTHON_LIBRARY})
set(EXTRA_LIBS ${EXTRA_LIBS} gpu)
file(GLOB SOURCE_FILES pybind/.cpp src/.cpp)
include_directories("./include")
include_directories(${CUDA_INCLUDE_DIRS})
include_directories(/usr${PYTHON_INCLUDE_DIR})
link_directories("-L${CUDA_TOOLKIT_ROOT_DIR}/lib64 -lcudart -lnppidei_static -lnppial_static -lnpps_static -lnppc_static -lculibos")
link_directories(${PYTHON_SO})
#.so
add_library(gpupreprocess SHARED ${SOURCE_FILES})
target_link_libraries(gpupreprocess ${EXTRA_LIBS})
target_link_libraries(gpupreprocess ${CUDA_LIBRARIES})
File: core/preprocess/hwvideoframe/README_ZN.md
hwvideoframe
hwvideoframe是一个基于cuda的图片预处理库。项目利用GPU进行图片预处理操作,在加快处理速度的同时,提高GPU的使用率。
项目结构
hwvideoframe目前提供以下图片预处理功能:
class Image2Gpubuffer
__call__(img)- img(np.array):输入图像。
class Gpubuffer2Image
__call__(img)- img(np.array):输入图像。
class Div
__init__(value)- value(float):根据固定值切割图像。
__call__(img)- img(np.array):输入图像。
class Sub
__init__(subtractor)- subtractor(list/float):list的长度必须为3。
__call__(img)- img(np.array):(C,H,W)排列的图像数据。
class Normalize
__init__(mean,std)- mean(list):均值。 list长度必须为3。
- std(list):方差。 list长度必须为3。
__call__(img)- img(np.array):(C,H,W)排列的图像数据。
class CenterCrop
__init__(size)- size(int):预期的裁剪后的大小,list类型时需要包含预期的长和宽,int类型时会返回边长为size的正方形图片。size不能大于原始图片大小。
__call__(img)- img(np.array):(C,H,W)排列的图像数据
class Resize
__init__(size, max_size=2147483647, interpolation=None)- size(list/int):预期的图像大小,短边会设置为size的长度,长边按比例缩放.
__call__(img)- img(numpy array):(C,H,W)排列的图像数据
快速开始
按照Paddle Serving文档编译,编译结果在reader中。
测试
测试文件:Serving/python/paddle_serving_app/reader/test_preprocess.py
File: core/preprocess/hwvideoframe/cuda/CMakeLists.txt
cmake_minimum_required(VERSION 3.2)
project(gpu)
FIND_PACKAGE(CUDA ${CUDA_VERSION} REQUIRED)
SET(CUDA_TARGET_INCLUDE ${CUDA_TOOLKIT_ROOT_DIR}-${CUDA_VERSION}/targets/${CMAKE_HOST_SYSTEM_PROCESSOR}-${LOWER_SYSTEM_NAME}/include)
file(GLOB_RECURSE CURRENT_HEADERS *.h *.hpp *.cuh)
file(GLOB CURRENT_SOURCES *.cpp *.cu)
source_group("Include" FILES ${CURRENT_HEADERS})
source_group("Source" FILES ${CURRENT_SOURCES})
set(CMAKE_CUDA_FLAGS "-ccbin /opt/compiler/gcc-4.8.2/bin -Xcompiler -fPIC --std=c++11")
set(CUDA_NVCC_FLAGS "-L/opt/compiler/gcc-4.8.2/bin -Xcompiler -fPIC --std=c++11")
include_directories(${CUDA_INCLUDE_DIRS})
cuda_add_library(gpu SHARED ${CURRENT_HEADERS} ${CURRENT_SOURCES})
target_link_libraries(gpu ${CUDA_LIBS})
File: core/sdk-cpp/CMakeLists.txt
include(src/CMakeLists.txt)
include(proto/CMakeLists.txt)
add_library(sdk-cpp ${sdk_cpp_srcs})
add_dependencies(sdk-cpp pdcodegen configure protobuf brpc leveldb)
target_link_libraries(sdk-cpp brpc configure protobuf leveldb)
install
install(TARGETS sdk-cpp
ARCHIVE DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/lib
)
install(DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/include
DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/include/core/sdk-cpp/)
FILE(GLOB inc ${CMAKE_CURRENT_BINARY_DIR}/*.pb.h)
install(FILES ${inc}
DESTINATION ${PADDLE_SERVING_INSTALL_DIR}/include/core/sdk-cpp)
File: core/sdk-cpp/proto/CMakeLists.txt
function(PROTOBUF_GENERATE_SERVING_CPP FOR_SERVING_SIDE SRCS HDRS )
if(NOT ARGN)
message(SEND_ERROR "Error: PROTOBUF_GENERATE_SERVING_CPP() called without any proto files")
return()
endif()
if(PROTOBUF_GENERATE_CPP_APPEND_PATH)
# Create an include path for each file specified
foreach(FIL ${ARGN})
get_filename_component(ABS_FIL ${FIL} ABSOLUTE)
get_filename_component(ABS_PATH ${ABS_FIL} PATH)
list(FIND _protobuf_include_path ${ABS_PATH} _contains_already)
if(${_contains_already} EQUAL -1)
list(APPEND _protobuf_include_path -I ${ABS_PATH})
endif()
endforeach()
else()
set(_protobuf_include_path -I ${CMAKE_CURRENT_SOURCE_DIR})
endif()
if(DEFINED PROTOBUF_IMPORT_DIRS)
foreach(DIR ${Protobuf_IMPORT_DIRS})
get_filename_component(ABS_PATH ${DIR} ABSOLUTE)
list(FIND _protobuf_include_path ${ABS_PATH} _contains_already)
if(${_contains_already} EQUAL -1)
list(APPEND _protobuf_include_path -I ${ABS_PATH})
endif()
endforeach()
endif()
set(${SRCS})
set(${HDRS})
foreach(FIL ${ARGN})
get_filename_component(ABS_FIL ${FIL} ABSOLUTE)
get_filename_component(FIL_WE ${FIL} NAME_WE)
list(APPEND ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.cc")
list(APPEND ${HDRS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.h")
set(PDCODEGEN "${CMAKE_BINARY_DIR}/core/pdcodegen/pdcodegen")
if (${FOR_SERVING_SIDE})
add_custom_command(
OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.cc"
"${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.h"
COMMAND ${Protobuf_PROTOC_EXECUTABLE}
ARGS --cpp_out=${CMAKE_CURRENT_BINARY_DIR}
--pdcodegen_out=${CMAKE_CURRENT_BINARY_DIR}
--plugin=protoc-gen-pdcodegen=${CMAKE_BINARY_DIR}/core/pdcodegen/pdcodegen
--proto_path=${CMAKE_SOURCE_DIR}/core/predictor/proto
${_protobuf_include_path} ${ABS_FIL}
DEPENDS ${ABS_FIL} ${Protobuf_PROTOC_EXECUTABLE} ${PDCODEGEN}
COMMENT "Running Paddle-serving C++ protocol buffer compiler on ${FIL}"
VERBATIM)
else()
add_custom_command(
OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.cc"
"${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.h"
COMMAND ${Protobuf_PROTOC_EXECUTABLE}
ARGS --cpp_out=${CMAKE_CURRENT_BINARY_DIR}
--pdcodegen_out=${CMAKE_CURRENT_BINARY_DIR}
--plugin=protoc-gen-pdcodegen=${CMAKE_BINARY_DIR}/core/pdcodegen/pdcodegen
${_protobuf_include_path} ${ABS_FIL}
DEPENDS ${ABS_FIL} ${Protobuf_PROTOC_EXECUTABLE} ${PDCODEGEN}
COMMENT "Running Paddle-serving C++ protocol buffer compiler on ${FIL}"
VERBATIM)
endif()endforeach()
set_source_files_properties(${${SRCS}} ${${HDRS}} PROPERTIES GENERATED TRUE)
set(${SRCS} ${${SRCS}} PARENT_SCOPE)
set(${HDRS} ${${HDRS}} PARENT_SCOPE)
endfunction()
FILE(GLOB protos ${CMAKE_CURRENT_LIST_DIR}/*.proto)
list(APPEND protos ${CMAKE_SOURCE_DIR}/core//predictor/proto/pds_option.proto
${CMAKE_SOURCE_DIR}/core//predictor/proto/builtin_format.proto)
PROTOBUF_GENERATE_SERVING_CPP(FALSE PROTO_SRCS PROTO_HDRS ${protos})
LIST(APPEND sdk_cpp_srcs ${PROTO_SRCS})
File: core/sdk-cpp/src/CMakeLists.txt
FILE(GLOB srcs ${CMAKE_CURRENT_LIST_DIR}/*.cpp)
LIST(APPEND sdk_cpp_srcs ${srcs})
File: core/util/CMakeLists.txt
include(src/CMakeLists.txt)
add_library(utils ${util_srcs})
File: core/util/src/CMakeLists.txt
FILE(GLOB srcs ${CMAKE_CURRENT_LIST_DIR}/*.cc)
LIST(APPEND util_srcs ${srcs})
File: doc/Check_Env_CN.md
Paddle Serving 环境检查功能介绍
概览
Paddle Serving 提供了一键运行示例,检查 Paddle Serving 环境是否安装正确。
启动方式
python3 -m paddle_serving_server.serve check| 命令 | 描述 |
|---|---|
| check_all | 检查 Paddle Inference、Pipeline Serving、C++ Serving。只打印检测结果,不记录日志 |
| check_pipeline | 检查 Pipeline Serving,只打印检测结果,不记录日志 |
| check_cpp | 检查 C++ Serving,只打印检测结果,不记录日志 |
| check_inference | 检查 Paddle Inference 是否安装正确,只打印检测结果,不记录日志 |
| debug | 发生报错后,该命令将打印提示日志到屏幕,并记录详细日志文件 |
| exit | 退出 |
注意:
1.当 C++ Serving 启动报错且是自己编译后 pip 安装的paddle_serving_server, 确认是否执行export SERVING_BIN导入SERVING_BIN真实路径。
2.可以通过export SERVING_LOG_PATH指定debug命令生成log的路径,默认是在当前路径下记录日志。
File: doc/Compile_CN.md
如何编译PaddleServing
(简体中文|English)
总体概述
编译Paddle Serving一共分以下几步
- 编译环境准备:根据模型和运行环境的需要,选择最合适的镜像
- 下载代码库:下载Serving代码库,按需要执行初始化操作
- 环境变量准备:根据运行环境的需要,确定Python各个环境变量,如GPU环境还需要确定Cuda,Cudnn,TensorRT等环境变量。
- 正式编译: 编译
paddle-serving-server,paddle-serving-client,paddle-serving-app相关whl包 - 安装相关whl包:安装编译出的三个whl包,并设置SERVING_BIN环境变量
此外,针对某些C++二次开发场景,我们也提供了OPENCV的联编方案。
编译环境准备
| 组件 | 版本要求 |
|---|---|
| OS | Ubuntu16 and 18/CentOS 7 |
| gcc | 5.4.0(Cuda 10.1) and 8.2.0 |
| gcc-c++ | 5.4.0(Cuda 10.1) and 8.2.0 |
| cmake | 3.2.0 and later |
| Python | 3.6.0 and later |
| Go | 1.17.2 and later |
| git | 2.17.1 and later |
| glibc-static | 2.17 |
| openssl-devel | 1.0.2k |
| bzip2-devel | 1.0.6 and later |
| python-devel / python3-devel | 3.6.0 and later |
| sqlite-devel | 3.7.17 and later |
| patchelf | 0.9 |
| libXext | 1.3.3 |
| libSM | 1.2.2 |
| libXrender | 0.9.10 |
推荐使用Docker编译,我们已经为您准备好了Paddle Serving编译环境并配置好了上述编译依赖,详见该文档。
我们提供了五个环境的开发镜像,分别是CPU、 CUDA10.1+CUDNN7、CUDA10.2+CUDNN8、 CUDA11.2+CUDNN8。我们提供了Serving开发镜像涵盖以上环境。与此同时,我们也支持Paddle开发镜像。
Serving开发镜像是Serving套件为了支持各个预测环境提供的用于编译、调试预测服务的镜像,Paddle开发镜像是Paddle在官网发布的用于编译、开发、训练模型使用镜像。为了让Paddle开发者能够在同一个容器内直接使用Serving。对于上个版本就已经使用Serving用户的开发者来说,Serving开发镜像应该不会感到陌生。但对于熟悉Paddle训练框架生态的开发者,目前应该更熟悉已有的Paddle开发镜像。为了适应所有用户的不同习惯,我们对这两套镜像都做了充分的支持。
| 环境 | Serving开发镜像Tag | 操作系统 | Paddle开发镜像Tag | 操作系统 |
|---|---|---|---|---|
| CPU | 0.9.0-devel | Ubuntu 16.04 | 2.3.0 | Ubuntu 18.04. |
| CUDA10.1 + CUDNN7 | 0.9.0-cuda10.1-cudnn7-devel | Ubuntu 16.04 | 无 | 无 |
| CUDA10.2 + CUDNN8 | 0.9.0-cuda10.2-cudnn8-devel | Ubuntu 16.04 | 无 | 无 |
| CUDA11.2 + CUDNN8 | 0.9.0-cuda11.2-cudnn8-devel | Ubuntu 16.04 | 2.3.0-gpu-cuda11.2-cudnn8 | Ubuntu 18.04 |
我们首先要针对自己所需的环境拉取相关镜像。上表环境一列下,除了CPU,其余(Cuda**+Cudnn**)都属于GPU环境。
您可以使用Serving开发镜像。
docker pull registry.baidubce.com/paddlepaddle/serving:${Serving开发镜像Tag}
# 如果是GPU镜像
nvidia-docker run --rm -it registry.baidubce.com/paddlepaddle/serving:${Serving开发镜像Tag} bash
# 如果是CPU镜像
docker run --rm -it registry.baidubce.com/paddlepaddle/serving:${Serving开发镜像Tag} bash也可以使用Paddle开发镜像。
docker pull registry.baidubce.com/paddlepaddle/paddle:${Paddle开发镜像Tag}
# 如果是GPU镜像,需要使用nvidia-docker
nvidia-docker run --rm -it registry.baidubce.com/paddlepaddle/paddle:${Paddle开发镜像Tag} bash
# 如果是CPU镜像
docker run --rm -it registry.baidubce.com/paddlepaddle/paddle:${Paddle开发镜像Tag} bash下载代码库
注明: 如果您正在使用Paddle开发镜像,需要在下载代码库后手动运行bash env_install.sh(如代码框的第三行所示)
git clone https://github.com/PaddlePaddle/Serving
cd Serving && git submodule update --init --recursive
# Paddle开发镜像需要运行如下命令,Serving开发镜像不需要运行
bash tools/paddle_env_install.sh环境变量准备
设置PYTHON环境变量
如果您使用的是Serving开发镜像,请按照如下,确定好需要编译的Python版本,设置对应的环境变量,一共需要设置三个环境变量,分别是PYTHON_INCLUDE_DIR, PYTHON_LIBRARIES, PYTHON_EXECUTABLE。以下我们以python 3.7为例,介绍如何设置这三个环境变量。
- 设置
PYTHON_INCLUDE_DIR
搜索Python.h 所在的目录
find / -name Python.h通常会有类似于**/include/python3.7/Python.h出现,我们只需要取它的文件夹目录就好,比如找到/usr/include/python3.7/Python.h,那么我们只需要export PYTHON_INCLUDE_DIR=/usr/include/python3.7/就好。
如果没有找到。说明 1)没有安装开发版本的Python,需重新安装 2)权限不足无法查看相关系统目录。
- 设置
PYTHON_LIBRARIES
搜索 libpython3.7.so 或 libpython3.7m.so
find / -name libpython3.7.so
find / -name libpython3.7m.so通常会有类似于**/lib/libpython3.7.so或者**/lib/x86_64-linux-gnu/libpython3.7.so出现,我们只需要取它的文件夹目录就好,比如找到/usr/local/lib/libpython3.7.so,那么我们只需要export PYTHON_LIBRARIES=/usr/local/lib就好。
如果没有找到,说明 1)静态编译Python,需要重新安装动态编译的Python 2)全县不足无法查看相关系统目录。
- 设置
PYTHON_EXECUTABLE
直接查看python3.7路径
which python3.7假如结果是/usr/local/bin/python3.7,那么直接设置export PYTHON_EXECUTABLE=/usr/local/bin/python3.7。
设置好这三个环境变量至关重要,设置完成后,我们便可以执行下列操作(以下是Paddle Cuda 11.2的开发镜像的PYTHON环境,如果是其他镜像,请更改相应的PYTHON_INCLUDE_DIR, PYTHON_LIBRARIES, PYTHON_EXECUTABLE)。
# 以下三个环境变量是Paddle开发镜像Cuda11.2的环境,如其他镜像可能需要修改
export PYTHON_INCLUDE_DIR=/usr/include/python3.7m/
export PYTHON_LIBRARIES=/usr/lib/x86_64-linux-gnu/libpython3.7m.so
export PYTHON_EXECUTABLE=/usr/bin/python3.7
export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin
python3.7 -m pip install -r python/requirements.txt
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct
go install github.com/grpc-ecosystem/grpc-gateway/[email protected]
go install github.com/grpc-ecosystem/grpc-gateway/[email protected]
go install github.com/golang/protobuf/[email protected]
go install google.golang.org/[email protected]
go env -w GO111MODULE=auto如果您是GPU用户需要额外设置CUDA_PATH, CUDNN_LIBRARY, CUDA_CUDART_LIBRARY和TENSORRT_LIBRARY_PATH。
export CUDA_PATH='/usr/local/cuda'
export CUDNN_LIBRARY='/usr/local/cuda/lib64/'
export CUDA_CUDART_LIBRARY="/usr/local/cuda/lib64/"
export TENSORRT_LIBRARY_PATH="/usr/"环境变量的含义如下表所示。
| cmake环境变量 | 含义 | GPU环境注意事项 | Docker环境是否需要 |
|---|---|---|---|
| CUDA_TOOLKIT_ROOT_DIR | cuda安装路径,通常为/usr/local/cuda | 全部GPU环境都需要 | 否(/usr/local/cuda) |
| CUDNN_LIBRARY | libcudnn.so.*所在目录,通常为/usr/local/cuda/lib64/ | 全部GPU环境都需要 | 否(/usr/local/cuda/lib64/) |
| CUDA_CUDART_LIBRARY | libcudart.so.*所在目录,通常为/usr/local/cuda/lib64/ | 全部GPU环境都需要 | 否(/usr/local/cuda/lib64/) |
| TENSORRT_ROOT | libnvinfer.so.*所在目录的上一级目录,取决于TensorRT安装目录 | 全部GPU环境都需要 | 否(/usr) |
正式编译
我们一共需要编译三个目标,分别是paddle-serving-server, paddle-serving-client, paddle-serving-app,其中paddle-serving-server需要区分CPU或者GPU版本。如果是CPU版本请运行,
编译paddle-serving-server
mkdir build_server
cd build_server
cmake -DPYTHON_INCLUDE_DIR=$PYTHON_INCLUDE_DIR \
-DPYTHON_LIBRARIES=$PYTHON_LIBRARIES \
-DPYTHON_EXECUTABLE=$PYTHON_EXECUTABLE \
-DSERVER=ON \
-DWITH_GPU=OFF ..
make -j20
cd ..如果是GPU版本,请运行,
mkdir build_server
cd build_server
cmake -DPYTHON_INCLUDE_DIR=$PYTHON_INCLUDE_DIR \
-DPYTHON_LIBRARIES=$PYTHON_LIBRARIES \
-DPYTHON_EXECUTABLE=$PYTHON_EXECUTABLE \
-DCUDA_TOOLKIT_ROOT_DIR=${CUDA_PATH} \
-DCUDNN_LIBRARY=${CUDNN_LIBRARY} \
-DCUDA_CUDART_LIBRARY=${CUDA_CUDART_LIBRARY} \
-DTENSORRT_ROOT=${TENSORRT_LIBRARY_PATH} \
-DSERVER=ON \
-DWITH_GPU=ON ..
make -j20
cd ..编译paddle-serving-client 和 paddle-serving-app
接下来,我们继续编译client和app就可以了,这两个包的编译命令在所有平台通用,不区分CPU和GPU的版本。
# 编译paddle-serving-client
mkdir build_client
cd build_client
cmake -DPYTHON_INCLUDE_DIR=$PYTHON_INCLUDE_DIR \
-DPYTHON_LIBRARIES=$PYTHON_LIBRARIES \
-DPYTHON_EXECUTABLE=$PYTHON_EXECUTABLE \
-DCLIENT=ON ..
make -j10
cd ..
# 编译paddle-serving-app
mkdir build_app
cd build_app
cmake -DPYTHON_INCLUDE_DIR=$PYTHON_INCLUDE_DIR \
-DPYTHON_LIBRARIES=$PYTHON_LIBRARIES \
-DPYTHON_EXECUTABLE=$PYTHON_EXECUTABLE \
-DAPP=ON ..
make -j10
cd ..安装相关whl包
pip3.7 install build_server/python/dist/*.whl
pip3.7 install build_client/python/dist/*.whl
pip3.7 install build_app/python/dist/*.whl
export SERVING_BIN=${PWD}/build_server/core/general-server/serving注意事项
注意到上一小节的最后一行export SERVING_BIN,运行python端Server时,会检查SERVING_BIN环境变量,如果想使用自己编译的二进制文件,请将设置该环境变量为对应二进制文件的路径,通常是export SERVING_BIN=${BUILD_DIR}/core/general-server/serving。
其中BUILD_DIR为build_server的绝对路径。
可以cd build_server路径下,执行export SERVING_BIN=${PWD}/core/general-server/serving
开启WITH_OPENCV选项编译C++ Server
注意: 只有当您需要对Paddle Serving C++部分进行二次开发,且新增的代码依赖于OpenCV库时,您才需要这样做。
编译Serving C++ Server部分,开启WITH_OPENCV选项时,需要已安装的OpenCV库,若尚未安装,可参考本文档后面的说明编译安装OpenCV库。
以开启WITH_OPENCV选项,编译CPU版本Paddle Inference Library为例,在上述编译命令基础上,加入DOPENCV_DIR=${OPENCV_DIR} 和 DWITH_OPENCV=ON选项。
OPENCV_DIR=your_opencv_dir #`your_opencv_dir`为opencv库的安装路径。
mkdir build_server && cd build_server
cmake -DPYTHON_INCLUDE_DIR=$PYTHON_INCLUDE_DIR/ \
-DPYTHON_LIBRARIES=$PYTHON_LIBRARIES \
-DPYTHON_EXECUTABLE=$PYTHON_EXECUTABLE \
-DOPENCV_DIR=${OPENCV_DIR} \
-DWITH_OPENCV=ON \
-DSERVER=ON ..
make -j10注意: 编译成功后,需要设置SERVING_BIN路径。
附:CMake选项说明
| 编译选项 | 说明 | 默认 |
|---|---|---|
| WITH_AVX | Compile Paddle Serving with AVX intrinsics | OFF |
| WITH_MKL | Compile Paddle Serving with MKL support | OFF |
| WITH_GPU | Compile Paddle Serving with NVIDIA GPU | OFF |
| WITH_TRT | Compile Paddle Serving with TensorRT | OFF |
| WITH_OPENCV | Compile Paddle Serving with OPENCV | OFF |
| CUDNN_LIBRARY | Define CuDNN library and header path | |
| CUDA_TOOLKIT_ROOT_DIR | Define CUDA PATH | |
| TENSORRT_ROOT | Define TensorRT PATH | |
| CLIENT | Compile Paddle Serving Client | OFF |
| SERVER | Compile Paddle Serving Server | OFF |
| APP | Compile Paddle Serving App package | OFF |
| PACK | Compile for whl | OFF |
WITH_GPU选项
Paddle Serving通过PaddlePaddle预测库支持在GPU上做预测。WITH_GPU选项用于检测系统上CUDA/CUDNN等基础库,如检测到合适版本,在编译PaddlePaddle时就会编译出GPU版本的OP Kernel。
在裸机上编译Paddle Serving GPU版本,需要安装这些基础库:
- CUDA
- CuDNN
编译TensorRT版本,需要安装TensorRT库。
这里要注意的是:
- 编译Serving所在的系统上所安装的CUDA/CUDNN等基础库版本,需要兼容实际的GPU设备。例如,Tesla V100卡至少要CUDA 9.0。如果编译时所用CUDA等基础库版本过低,由于生成的GPU代码和实际硬件设备不兼容,会导致Serving进程无法启动,或出现coredump等严重问题。
- 运行Paddle Serving的系统上安装与实际GPU设备兼容的CUDA driver,并安装与编译期所用的CUDA/CuDNN等版本兼容的基础库。如运行Paddle Serving的系统上安装的CUDA/CuDNN的版本低于编译时所用版本,可能会导致奇怪的cuda函数调用失败等问题。
以下是PaddleServing 镜像的Cuda与Cudnn,TensorRT的匹配关系,供参考:
| CUDA | CuDNN | TensorRT | |
|---|---|---|---|
| post101 | 10.1 | CuDNN 7.6.5 | 6.0.1 |
| post102 | 10.2 | CuDNN 8.0.5 | 7.1.3 |
| post11 | 11.0 | CuDNN 8.0.4 | 7.1.3 |
附:如何让Paddle Serving编译系统探测到CuDNN库
从NVIDIA developer官网下载对应版本CuDNN并在本地解压后,在cmake编译命令中增加-DCUDNN_LIBRARY参数,指定CuDNN库所在路径。
附:编译安装OpenCV库
注意: 只有当您需要在C++代码中引入OpenCV库时,您才需要这样做。
- 首先需要从OpenCV官网上下载在Linux环境下源码编译的包,以OpenCV3.4.7为例,下载命令如下。
wget https://github.com/opencv/opencv/archive/3.4.7.tar.gz
tar -xf 3.4.7.tar.gz最终可以在当前目录下看到opencv-3.4.7/的文件夹。
- 编译OpenCV,设置OpenCV源码路径(
root_path)以及安装路径(install_path)。进入OpenCV源码路径下,按照下面的方式进行编译。
root_path=your_opencv_root_path
install_path=${root_path}/opencv3
rm -rf build
mkdir build
cd build
cmake .. \
-DCMAKE_INSTALL_PREFIX=${install_path} \
-DCMAKE_BUILD_TYPE=Release \
-DBUILD_SHARED_LIBS=OFF \
-DWITH_IPP=OFF \
-DBUILD_IPP_IW=OFF \
-DWITH_LAPACK=OFF \
-DWITH_EIGEN=OFF \
-DCMAKE_INSTALL_LIBDIR=lib64 \
-DWITH_ZLIB=ON \
-DBUILD_ZLIB=ON \
-DWITH_JPEG=ON \
-DBUILD_JPEG=ON \
-DWITH_PNG=ON \
-DBUILD_PNG=ON \
-DWITH_TIFF=ON \
-DBUILD_TIFF=ON
make -j
make install其中root_path为下载的OpenCV源码路径,install_path为OpenCV的安装路径,make install完成之后,会在该文件夹下生成OpenCV头文件和库文件,用于引用OpenCV库的代码的编译。
最终在安装路径下的文件结构如下所示。
opencv3/
|-- bin
|-- include
|-- lib
|-- lib64
|-- shareFile: doc/Compile_EN.md
How to compile PaddleServing
(简体中文|English)
Overview
Compiling Paddle Serving is divided into the following steps
- Compilation Environment Preparation: According to the needs of the model and operating environment, select the most suitable image
- Download the Serving Code Repo: Download the Serving code library, and perform initialization operations as needed
- Environment Variable Preparation: According to the needs of the running environment, determine the various environment variables of Python. For example, the GPU environment also needs to determine the environment variables such as Cuda, Cudnn, TensorRT and so on.
- Compilation: Compile
paddle-serving-server,paddle-serving-client,paddle-serving-apprelated whl packages - Install Related Whl Packages: install the three compiled whl packages, and set the SERVING_BIN environment variable
In addition, for some C++ secondary development scenarios, we also provide OPENCV binding solutions.
Compilation Environment Requirements
| module | version |
|---|---|
| OS | Ubuntu16 and 18/CentOS 7 |
| gcc | 5.4.0(Cuda 10.1) and 8.2.0 |
| gcc-c++ | 5.4.0(Cuda 10.1) and 8.2.0 |
| cmake | 3.2.0 and later |
| Python | 3.6.0 and later |
| Go | 1.17.2 and later |
| git | 2.17.1 and later |
| glibc-static | 2.17 |
| openssl-devel | 1.0.2k |
| bzip2-devel | 1.0.6 and later |
| python3-devel | 3.6.0 and later |
| sqlite-devel | 3.7.17 and later |
| patchelf | 0.9 |
| libXext | 1.3.3 |
| libSM | 1.2.2 |
| libXrender | 0.9.10 |
Docker compilation is recommended. We have prepared the Paddle Serving compilation environment for you and configured the above compilation dependencies. For details, please refer to this document.
We provide 4 environment development images, namely CPU, CUDA10.2 + CUDNN7, CUDA10.2 + CUDNN8, CUDA11.2 + CUDNN8. We provide a Serving development image to cover the above environment. At the same time, we also support Paddle development mirroring.
Serving development mirror is the mirror used to compile and debug prediction services provided by Serving suite in order to support various prediction environments. Paddle development mirror is the mirror used for compilation, development, and training models released by Paddle on the official website. In order to allow Paddle developers to use Serving directly in the same container. For developers who have already used Serving users in the previous version, Serving development image should not be unfamiliar. But for developers who are familiar with the Paddle training framework ecology, they should be more familiar with the existing Paddle development mirrors. In order to adapt to the different habits of all users, we have fully supported both sets of mirrors.
| Environment | Serving Dev Image Tag | OS | Paddle Dev Image Tag | OS |
|---|---|---|---|---|
| CPU | 0.9.0-devel | Ubuntu 16.04 | 2.3.0 | Ubuntu 18.04. |
| CUDA10.1 + Cudnn7 | 0.9.0-cuda10.1-cudnn7-devel | Ubuntu 16.04 | Nan | Nan |
| CUDA10.2 + Cudnn8 | 0.9.0-cuda10.2-cudnn8-devel | Ubuntu 16.04 | Nan | Nan |
| CUDA11.2 + Cudnn8 | 0.9.0-cuda11.2-cudnn8-devel | Ubuntu 16.04 | 2.3.0-gpu-cuda11.2-cudnn8 | Ubuntu 18.04 |
We first need to pull related images for the environment we need. Under the Environment column in the above table, except for the CPU, the rest (Cuda**+Cudnn**) belong to the GPU environment.
You can use Serving Dev Images.
docker pull registry.baidubce.com/paddlepaddle/serving:${Serving Dev Image Tag}
# For GPU Image
nvidia-docker run --rm -it registry.baidubce.com/paddlepaddle/serving:${Serving Dev Image Tag} bash
# For CPU Image
docker run --rm -it registry.baidubce.com/paddlepaddle/serving:${Serving Dev Image Tag} bashYou can also use Paddle Dev Images.
docker pull registry.baidubce.com/paddlepaddle/paddle:${Paddle Dev Image Tag}
# For GPU Image
nvidia-docker run --rm -it registry.baidubce.com/paddlepaddle/paddle:${Paddle Dev Image Tag} bash
# For CPU Image
docker run --rm -it registry.baidubce.com/paddlepaddle/paddle:${Paddle Dev Image Tag} bashDownload the Serving Code Repo
Note: If you are using Paddle to develop the image, you need to manually run bash env_install.sh after downloading the code base (as shown in the third line of the code box)
git clone https://github.com/PaddlePaddle/Serving
cd Serving && git submodule update --init --recursive
# Paddle development image needs to run the following commands, Serving development image does not need to run
bash tools/paddle_env_install.shEnvironment Variables Preparation
Set PYTHON environment variable
If you are using a Serving development image, please follow the steps below to determine the Python version that needs to be compiled and set the corresponding environment variables. A total of three environment variables need to be set, namely PYTHON_INCLUDE_DIR, PYTHON_LIBRARIES, PYTHON_EXECUTABLE. Below we take python 3.7 as an example to introduce how to set these three environment variables.
- Set
PYTHON_INCLUDE_DIR
Search the directory where Python.h is located
find / -name Python.hUsually there will be something like **/include/python3.7/Python.h, we only need to take its folder directory, for example, find /usr/include/python3.7/Python.h, Then we only need export PYTHON_INCLUDE_DIR=/usr/include/python3.7/.
If not found. Explanation 1) The development version of Python is not installed and needs to be re-installed. 2) Insufficient permissions cannot view the relevant system directories.
- Set
PYTHON_LIBRARIES
Search for libpython3.7.so or libpython3.7m.so
find / -name libpython3.7.so
find / -name libpython3.7m.soUsually there will be something similar to **/lib/libpython3.7.so or **/lib/x86_64-linux-gnu/libpython3.7.so, we only need to take its folder directory, For example, find /usr/local/lib/libpython3.7.so, then we only need export PYTHON_LIBRARIES=/usr/local/lib.
If it is not found, it means 1) Statically compiling Python, you need to reinstall the dynamically compiled Python 2) The county is not enough to view the relevant system catalogs.
- Set
PYTHON_EXECUTABLE
View the python3.7 path directly
which python3.7If the result is /usr/local/bin/python3.7, then directly set export PYTHON_EXECUTABLE=/usr/local/bin/python3.7.
It is very important to set these three environment variables. After the settings are completed, we can perform the following operations (the following is the PYTHON environment of the development image of Paddle Cuda 11.2, if it is another image, please change the corresponding PYTHON_INCLUDE_DIR, PYTHON_LIBRARIES , PYTHON_EXECUTABLE).
# The following three environment variables are the environment of Paddle development mirror Cuda11.2, such as other mirrors may need to be modified
export PYTHON_INCLUDE_DIR=/usr/include/python3.7m/
export PYTHON_LIBRARIES=/usr/lib/x86_64-linux-gnu/libpython3.7m.so
export PYTHON_EXECUTABLE=/usr/bin/python3.7
export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin
python3.7 -m pip install -r python/requirements.txt
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct
go install github.com/grpc-ecosystem/grpc-gateway/[email protected]
go install github.com/grpc-ecosystem/grpc-gateway/[email protected]
go install github.com/golang/protobuf/[email protected]
go install google.golang.org/[email protected]
go env -w GO111MODULE=autoIf you are a GPU user, you need to set additional CUDA_PATH, CUDNN_LIBRARY, CUDA_CUDART_LIBRARY and TENSORRT_LIBRARY_PATH.
export CUDA_PATH='/usr/local/cuda'
export CUDNN_LIBRARY='/usr/local/cuda/lib64/'
export CUDA_CUDART_LIBRARY="/usr/local/cuda/lib64/"
export TENSORRT_LIBRARY_PATH="/usr/"The meaning of environment variables is shown in the table below.
| cmake environment variable | meaning | GPU environment considerations | whether Docker environment is needed |
|---|---|---|---|
| CUDA_TOOLKIT_ROOT_DIR | cuda installation path, usually /usr/local/cuda | Required for all environments | No (/usr/local/cuda) |
| CUDNN_LIBRARY | The directory where libcudnn.so.* is located, usually /usr/local/cuda/lib64/ | Required for all environments | No (/usr/local/cuda/lib64/) |
| CUDA_CUDART_LIBRARY | The directory where libcudart.so.* is located, usually /usr/local/cuda/lib64/ | Required for all environments | No (/usr/local/cuda/lib64/) |
| TENSORRT_ROOT | The upper level directory of the directory where libnvinfer.so.* is located, depends on the TensorRT installation directory | Required for all environments | No (/usr) |
Compilation
We need to compile three targets in total, namely paddle-serving-server, paddle-serving-client, and paddle-serving-app, among which paddle-serving-server needs to distinguish between CPU or GPU version. If it is a CPU version, please run,
Compile paddle-serving-server
mkdir build_server
cd build_server
cmake -DPYTHON_INCLUDE_DIR=$PYTHON_INCLUDE_DIR \
-DPYTHON_LIBRARIES=$PYTHON_LIBRARIES \
-DPYTHON_EXECUTABLE=$PYTHON_EXECUTABLE \
-DSERVER=ON \
-DWITH_GPU=OFF ..
make -j20
cd ..If it is the GPU version, please run,
mkdir build_server
cd build_server
cmake -DPYTHON_INCLUDE_DIR=$PYTHON_INCLUDE_DIR \
-DPYTHON_LIBRARIES=$PYTHON_LIBRARIES \
-DPYTHON_EXECUTABLE=$PYTHON_EXECUTABLE \
-DCUDA_TOOLKIT_ROOT_DIR=${CUDA_PATH} \
-DCUDNN_LIBRARY=${CUDNN_LIBRARY} \
-DCUDA_CUDART_LIBRARY=${CUDA_CUDART_LIBRARY} \
-DTENSORRT_ROOT=${TENSORRT_LIBRARY_PATH} \
-DSERVER=ON \
-DWITH_GPU=ON ..
make -j20
cd ..Compile paddle-serving-client and paddle-serving-app
Next, we can continue to compile the client and app. The compilation commands for these two packages are common on all platforms, and do not distinguish between CPU and GPU versions.
# Compile paddle-serving-client
mkdir build_client
cd build_client
cmake -DPYTHON_INCLUDE_DIR=$PYTHON_INCLUDE_DIR \
-DPYTHON_LIBRARIES=$PYTHON_LIBRARIES \
-DPYTHON_EXECUTABLE=$PYTHON_EXECUTABLE \
-DCLIENT=ON ..
make -j10
cd ..
# Compile paddle-serving-app
mkdir build_app
cd build_app
cmake -DPYTHON_INCLUDE_DIR=$PYTHON_INCLUDE_DIR \
-DPYTHON_LIBRARIES=$PYTHON_LIBRARIES \
-DPYTHON_EXECUTABLE=$PYTHON_EXECUTABLE \
-DAPP=ON ..
make -j10
cd ..Install Related Whl Packages
pip3.7 install build_server/python/dist/*.whl
pip3.7 install build_client/python/dist/*.whl
pip3.7 install build_app/python/dist/*.whl
export SERVING_BIN=${PWD}/build_server/core/general-server/servingPrecautions
Note the last line export SERVING_BIN in the previous section. When running the python server, the SERVING_BIN environment variable will be checked. If you want to use the binary file compiled by yourself, please set the environment variable to the path of the corresponding binary file. It is export SERVING_BIN=${BUILD_DIR}/core/general-server/serving.
Where BUILD_DIR is the absolute path of build_server.
You can cd build_server path and execute export SERVING_BIN=${PWD}/core/general-server/serving
Enable WITH_OPENCV option to compile C++ Server
Note: You only need to do this when you need to do secondary development on the Paddle Serving C++ part and the newly added code depends on the OpenCV library.
To compile the Serving C++ Server part, when the WITH_OPENCV option is turned on, the installed OpenCV library is required. If it has not been installed, you can refer to the instructions at the back of this document to compile and install the OpenCV library.
Take the WITH_OPENCV option and compile the CPU version Paddle Inference Library as an example. On the basis of the above compilation command, add the DOPENCV_DIR=${OPENCV_DIR} and DWITH_OPENCV=ON options.
OPENCV_DIR=your_opencv_dir #`your_opencv_dir` is the installation path of the opencv library.
mkdir build_server && cd build_server
cmake -DPYTHON_INCLUDE_DIR=$PYTHON_INCLUDE_DIR/ \
-DPYTHON_LIBRARIES=$PYTHON_LIBRARIES \
-DPYTHON_EXECUTABLE=$PYTHON_EXECUTABLE \
-DOPENCV_DIR=${OPENCV_DIR} \
-DWITH_OPENCV=ON \
-DSERVER=ON ..
make -j10Note: After the compilation is successful, you need to set the SERVING_BIN path.
Attached: CMake option description
| Compilation Options | Description | Default |
|---|---|---|
| WITH_AVX | Compile Paddle Serving with AVX intrinsics | OFF |
| WITH_MKL | Compile Paddle Serving with MKL support | OFF |
| WITH_GPU | Compile Paddle Serving with NVIDIA GPU | OFF |
| WITH_TRT | Compile Paddle Serving with TensorRT | OFF |
| WITH_OPENCV | Compile Paddle Serving with OPENCV | OFF |
| CUDNN_LIBRARY | Define CUDNN library and header path | |
| CUDA_TOOLKIT_ROOT_DIR | Define CUDA PATH | |
| TENSORRT_ROOT | Define TensorRT PATH | |
| CLIENT | Compile Paddle Serving Client | OFF |
| SERVER | Compile Paddle Serving Server | OFF |
| APP | Compile Paddle Serving App package | OFF |
| PACK | Compile for whl | OFF |
WITH_GPU option
Paddle Serving supports prediction on the GPU through the PaddlePaddle prediction library. The WITH_GPU option is used to detect basic libraries such as CUDA/CUDNN on the system. If a suitable version is detected, the GPU version of the OP Kernel will be compiled when the PaddlePaddle is compiled.
To compile the Paddle Serving GPU version on bare metal, you need to install these basic libraries:
-CUDA
-CUDNN
To compile the TensorRT version, you need to install the TensorRT library.
The things to note here are:
- Compile the basic library versions such as CUDA/CUDNN installed on the system where Serving is located, and need to be compatible with the actual GPU device. For example, Tesla V100 card requires at least CUDA 9.0. If the version of basic libraries such as CUDA used during compilation is too low, the Serving process cannot be started due to the incompatibility between the generated GPU code and the actual hardware device, or serious problems such as coredump may occur.
- Install the CUDA driver compatible with the actual GPU device on the system running Paddle Serving, and install the basic library compatible with the CUDA/CUDNN version used during compilation. If the version of CUDA/CUDNN installed on the system running Paddle Serving is lower than the version used during compilation, it may cause strange cuda function call failures and other problems.
The following is the matching relationship between PaddleServing mirrored Cuda, Cudnn, and TensorRT for reference:
| Tag | CUDA | CUDNN | TensorRT |
|---|---|---|---|
| post101 | 10.1 | CUDNN 7.6.5 | 6.0.1 |
| post102 | 10.2 | CUDNN 8.0.5 | 7.1.3 |
| post11 | 11.0 | CUDNN 8.0.4 | 7.1.3 |
Attachment: How to make the Paddle Serving compilation system detect the CUDNN library
After downloading the corresponding version of CUDNN from the official website of NVIDIA developer and decompressing it locally, add the -DCUDNN_LIBRARY parameter to the cmake compilation command and specify the path of the CUDNN library.
Attachment: Compile and install OpenCV library
Note: You only need to do this when you need to include the OpenCV library in your C++ code.
- First, you need to download the package compiled from the source code in the Linux environment from the OpenCV official website. Take OpenCV 3.4.7 as an example. The download command is as follows.
wget https://github.com/opencv/opencv/archive/3.4.7.tar.gz
tar -xf 3.4.7.tar.gzFinally, you can see the folder opencv-3.4.7/ in the current directory.
- Compile OpenCV, set the OpenCV source path (
root_path) and installation path (install_path). Enter the OpenCV source code path and compile in the following way.
root_path=your_opencv_root_path
install_path=${root_path}/opencv3
rm -rf build
mkdir build
cd build
cmake .. \
-DCMAKE_INSTALL_PREFIX=${install_path} \
-DCMAKE_BUILD_TYPE=Release \
-DBUILD_SHARED_LIBS=OFF \
-DWITH_IPP=OFF \
-DBUILD_IPP_IW=OFF \
-DWITH_LAPACK=OFF \
-DWITH_EIGEN=OFF \
-DCMAKE_INSTALL_LIBDIR=lib64 \
-DWITH_ZLIB=ON \
-DBUILD_ZLIB=ON \
-DWITH_JPEG=ON \
-DBUILD_JPEG=ON \
-DWITH_PNG=ON \
-DBUILD_PNG=ON \
-DWITH_TIFF=ON \
-DBUILD_TIFF=ON
make -j
make installAmong them, root_path is the downloaded OpenCV source path, install_path is the installation path of OpenCV, after the completion of make install, OpenCV header files and library files will be generated in this folder, which are used to compile the code that references the OpenCV library .
The final file structure under the installation path is as follows.
opencv3/
|-- bin
|-- include
|-- lib
|-- lib64
|-- shareFile: doc/Contribute_EN.md
Contribute Code
You are welcome to contribute to project Paddle Serving.
We sincerely appreciate your contribution. This document explains our workflow and work style.
Workflow
Paddle Serving uses this Git branching model. The following steps guide usual contributions.
Fork
Our development community has been growing fastly; it doesn't make sense for everyone to write into the official repo. So, please file Pull Requests from your fork. To make a fork, just head over to the GitHub page and click the "Fork" button.
Clone
To make a copy of your fork to your local computers, please run
bashgit clone https://github.com/your-github-account/Serving cd ServingCreate the local feature branch
For daily works like adding a new feature or fixing a bug, please open your feature branch before coding:
bashgit checkout -b my-cool-stuffCommit
Before issuing your first
git commitcommand, please installpre-commitby running the following commands:bashpip install pre-commit pre-commit installOur pre-commit configuration requires clang-format 3.8 for auto-formating C/C++ code and yapf for Python. At the same time, cpplint and pylint are required to check the code style of C/C++ and Python respectively. You may need to install cpplint and pylint by running the following commands:
bashpip install cpplint pylintOnce installed,
pre-commitchecks the style of code and documentation in every commit. We will see something like the following when you rungit commit:shell$ git commit CRLF end-lines remover...............................(no files to check)Skipped yapf.....................................................................Passed Check for added large files..............................................Passed Check for merge conflicts................................................Passed Check for broken symlinks................................................Passed Detect Private Key...................................(no files to check)Skipped Fix End of Files.........................................................Passed clang-format.............................................................Passed cpplint..................................................................Passed pylint...................................................................Passed copyright_checker........................................................Passed [my-cool-stuff c703c041] add test file 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 233NOTE: The
yapfinstalled bypip install pre-commitandconda install -c conda-forge pre-commitis slightly different. Paddle developers usepip install pre-commit.Build and test
Users can build Paddle Serving natively on Linux, see the BUILD steps.
Keep pulling
An experienced Git user pulls from the official repo often -- daily or even hourly, so they notice conflicts with others work early, and it's easier to resolve smaller conflicts.
bashgit remote add upstream https://github.com/PaddlePaddle/Serving git pull upstream developPush and file a pull request
You can "push" your local work into your forked repo:
bashgit push origin my-cool-stuffThe push allows you to create a pull request, requesting owners of this official repo to pull your change into the official one.
To create a pull request, please follow these steps.
If your change is for fixing an issue, please write "Fixes " in the description section of your pull request. Github would close the issue when the owners merge your pull request.
Please remember to specify some reviewers for your pull request. If you don't know who are the right ones, please follow Github's recommendation.
Delete local and remote branches
To keep your local workspace and your fork clean, you might want to remove merged branches:
bashgit push origin :my-cool-stuff git checkout develop git pull upstream develop git branch -d my-cool-stuff
Code Review
Please feel free to ping your reviewers by sending them the URL of your pull request via IM or email. Please do this after your pull request passes the CI.
Please answer reviewers' every comment. If you are to follow the comment, please write "Done"; please give a reason otherwise.
If you don't want your reviewers to get overwhelmed by email notifications, you might reply their comments by in a batch.
Reduce the unnecessary commits. Some developers commit often. It is recommended to append a sequence of small changes into one commit by running
git commit --amendinstead ofgit commit.
Coding Standard
Code Style
Our C/C++ code follows the Google style guide.
Our Python code follows the PEP8 style guide.
Please install pre-commit, which automatically reformat the changes to C/C++ and Python code whenever we run git commit. To check the whole codebase, we can run the command pre-commit run -a, which is invoked by [our Travis CI configuration].
Unit Tests
Please remember to add related unit tests.
For C/C++ code, please follow
google-testPrimer .For Python code, please use Python's standard
unittestpackage.
Writing Logs
We use glog for logging in our C/C++ code.
We use LOG() for general logging
LOG(INFO) << "Operator FC is taking " << num_inputs << "inputs."When we run a Paddle Serving application or test, we can specify a logging level. For example:
GLOG_minloglevel=1 bin/serving0 - INFO
1 - WARNING
2 - ERROR
3 - FATAL (Be careful as FATAL log will generate a coredump)
File: doc/Cube_Local_CN.md
稀疏参数索引服务Cube单机版使用指南
(简体中文|English)
引言
在python/examples下有两个关于CTR的示例,他们分别是criteo_ctr, criteo_ctr_with_cube。前者是在训练时保存整个模型,包括稀疏参数。后者是将稀疏参数裁剪出来,保存成两个部分,一个是稀疏参数,另一个是稠密参数。由于在工业级的场景中,稀疏参数的规模非常大,达到10^9数量级。因此在一台机器上启动大规模稀疏参数预测是不实际的,因此我们引入百度多年来在稀疏参数索引领域的工业级产品Cube,提供分布式的稀疏参数服务。
本文档使用的都是未经过任何压缩算法处理的原始模型,如果有量化模型上线需求,请阅读Cube稀疏参数索引量化存储使用指南
示例
在Serving/examples/C++/PaddleRec/criteo_ctr_with_cube/下执行
python local_train.py # 训练模型
cp ../../../build_server/core/predictor/seq_generator seq_generator #复制Sequence File模型生成工具
cp ../../../build_server/output/bin/cube* ./cube/ #复制Cube应用程序
cp ../../../build_server/core/cube/cube-api/cube-cli ./cube/ # 复制Cube-Cli
cube_prepare.sh & #启动配送脚本此示例是从模型训练到配送给Cube的全套流程,接下来会一一介绍。
单机版Cube组件介绍
cube-builder
cube-builder是把模型生成分片文件和版本管理的工具。由于cube是用于分布式的稀疏参数服务,对于分布式当中的每一个节点,需要加载不同的分片,然而生成的稀疏参数文件往往一个大文件,就需要用哈希函数将其分割为不同的分片。与此同时,工业级的场景需要支持定期模型的配送和流式训练,因此对于模型的版本管理十分重要,这也是在训练保存模型时缺失的部分,因此cube-builder在生成分片的同时,也可以人为指定增加版本信息。
cube-server
cube-server基于Cube的KV能力,对外提供稀疏参数服务,它通过brpc提供高性能分布式查询服务,通过RestAPI来进行远端调用。
cube-cli
cube-cli是cube-server的客户端,这部分已经被整合到paddle serving当中,当我们准备好cube.conf配置文件并在paddle serving server的代码中指定kv_infer相关的op时,cube-cli就会在serving端准备就绪。
模型配送步骤
前序步骤
需要训练出模型文件,并复制相关build_server目录下的应用程序
python local_train.py
cp ../../../build_server/core/predictor/seq_generator seq_generator #复制Sequence File模型生成工具
cp ../../../build_server/output/bin/cube* ./cube/ #复制Cube应用程序
cp ../../../build_server/core/cube/cube-api/cube-cli ./cube/ # 复制Cube-Cli模型文件生成Sequence File
为了让模型参数从训练端配送到预测端,我们需要把训练好的模型从Paddle 模型保存格式转换成Sequence File格式。
为什么是 Sequence File?
Sequence File是Hadoop File System的通用格式。在文章的开头提到了分布式Cube可以为超大规模稀疏参数服务提供支持,而大规模的稀疏参数在实际生产环境中保存在分布式文件系统当中,Hadoop File System是业界开源的最稳定的分布式文件系统之一,因此Sequence File格式成为了Cube加载模型的文件格式。
mkdir -p cube_model
mkdir -p cube/data
./seq_generator ctr_serving_model/SparseFeatFactors ./cube_model/feature生成分片文件
在单机版的环境下,分片数为1。执行
./cube/cube-builder -dict_name=test_dict -job_mode=base -last_version=0 -cur_version=0 -depend_version=0 -input_path=./cube_model -output_path=./cube/data -shard_num=1 -only_build=false配送给Cube-Server
单机版本的配送过程非常简单,只需要在cube二进制程序所在目录下的data文件夹存放index.前缀的文件即可。
mv ./cube/data/0_0/test_dict_part0/* ./cube/data/
cd cube && ./cube &Cube-Client 验证配送是否成功
此步非必须,用于测试配送是否成功
cd cube
./cube-cli -dict_name=test_dict -keys keys -conf ./cube/cube.conf如果查看到每个key都有对应的value输出,就说明配送成功。此文件也可以被Serving使用,用作Serving中 general kv infer op中进行cube查询。
如果执行成功,会看到如下结果
注: 配置文件
以Serving/examples/C++/PaddleRec/criteo_ctr_with_cube/cube/conf下的cube.conf示例,此文件被上述的cube-cli所使用,单机版用户可以直接使用不用关注此部分,它在分布式部署中更为重要。
[{
"dict_name": "test_dict", //表名
"shard": 1, //分片数
"dup": 1, //副本数
"timeout": 200,
"retry": 3,
"backup_request": 100,
"type": "ipport_list",
"load_balancer": "rr",
"nodes": [{
"ipport_list": "list://127.0.0.1:8027" //IP列表
}]
}]File: doc/Cube_Local_EN.md
Cube: Sparse Parameter Indexing Service (Local Mode)
(简体中文|English)
Overview
There are two examples on CTR under python / examples, they are criteo_ctr, criteo_ctr_with_cube. The former is to save the entire model during training, including sparse parameters. The latter is to cut out the sparse parameters and save them into two parts, one is the sparse parameter and the other is the dense parameter. Because the scale of sparse parameters is very large in industrial cases, reaching the order of 10 ^ 9. Therefore, it is not practical to start large-scale sparse parameter prediction on one machine. Therefore, we introduced Baidu's industrial-grade product Cube to provide the sparse parameter service for many years to provide distributed sparse parameter services.
The local mode of Cube is different from distributed Cube, which is designed to be convenient for developers to use in experiments and demos.
This document uses the original model without any compression algorithm. If there is a need for a quantitative model to go online, please read the Quantization Storage on Cube Sparse Parameter Indexing
Example
in directory Serving/examples/C++/PaddleRec/criteo_ctr_with_cube, run
python local_train.py # train model
cp ../../../build_server/core/predictor/seq_generator seq_generator # copy Sequence File generator
cp ../../../build_server/output/bin/cube* ./cube/ # copy Cube tool kits
cp ../../../build_server/core/cube/cube-api/cube-cli ./cube/ # copy Cube Client
cube_prepare.sh & # start deliver scriptyou will convert the Sparse Parameters from trained model to the Cube Server.
Components of Cube
cube-builder
cube-builder is a tool for generating model shard files and version management. As the cube is used for distributed sparse parameter services, for each node in the distribution, different shards need to be loaded. However, the generated sparse parameter file is often a large file, and it needs to be divided into different shards by a hash function. At the same time, industrial-level scenarios need to support regular model distribution and streaming training, so it is very important for the version management of the model. This is also the missing part when training and saving the model. Therefore, while the cube-builder generates the shards, You can also manually specify version information.
cube-server
The cube-server is based on the sparse parameter indexing, providing the sparse parameter service. It provides high-performance distributed query service through brpc, and makes remote calls through RestAPI.
cube-cli
cube-cli is the client of cube-server. This part has been integrated into paddle serving. When we prepare the cube.conf configuration file and specify the kv_infer related op in the code of paddle serving server, cube-cli will Ready on the serving side.
Serving the Model Step by Step
precondition
we need a trained model, and copy the tool kits from build_server folder.
python local_train.py # train model
cp ../../../build_server/core/predictor/seq_generator seq_generator # copy Sequence File generator
cp ../../../build_server/output/bin/cube* ./cube/ # copy Cube tool kits
cp ../../../build_server/core/cube/cube-api/cube-cli ./cube/ # copy Cube ClientGenerate Sequence File from Sparse Parameter
In order to get the model parameters from the training end to the prediction end, we need to convert the trained model from the Paddle model save format to the Sequence File format.
why is Sequence File?
Sequence File is a common format for the Hadoop File System. It was mentioned at the beginning of the article that distributed cubes can provide support for ultra-large-scale sparse parameter services, and large-scale sparse parameters are stored in distributed file systems in actual production environments. Hadoop File System is one of the most stable distributed open source. So the Sequence File format became the file format for the Cube loading model.
mkdir -p cube_model
mkdir -p cube/data
./seq_generator ctr_serving_model/SparseFeatFactors ./cube_model/featureGenerating Shards
For the local version of Cube, the number of shard is 1. run
cube-builder -dict_name=test_dict -job_mode=base -last_version=0 -cur_version=0 -depend_version=0 -input_path=./cube_model -output_path=./cube/data -shard_num=1 -only_build=falseDeliver to Cube-Server
The process of the cube local version is very simple, you only need to store the index files. in ./data folder where the cube binary program is located.
mv ./cube/data/0_0/test_dict_part0/* ./cube/data/
cd cube && ./cube &Cube-Client Verification
this step is not necessary, but it can help you to verify if the model is ready.
./cube-cli -dict_name=test_dict -keys keys -conf ./cube/cube.confif you succeed, you will see this
If you see that each key has a corresponding value output, it means that the delivery was successful. This file can also be used by Serving to perform cube query in general kv infer op in Serving.
Appendix: Configuration
the config file is cube.config located in Serving/examples/C++/PaddleRec/criteo_ctr_with_cube/cube/conf, this file is used by cube-cli.the Cube Local Mode users do not need to understand that just use it, it would be quite important in Cube Distributed Mode.
[{
"dict_name": "test_dict", //table name
"shard": 1, //shard num
"dup": 1, //duplicates
"timeout": 200,
"retry": 3,
"backup_request": 100,
"type": "ipport_list",
"load_balancer": "rr",
"nodes": [{
"ipport_list": "list://127.0.0.1:8027" //IP list
}]
}]File: doc/Cube_Quant_CN.md
Cube稀疏参数索引量化存储使用指南
(简体中文|English)
总体概览
我们在之前的文章中,知道稀疏参数是维度很大的一系列浮点数,而浮点数在计算机中需要4 Byte的存储空间。事实上,我们并不需要很高的浮点数精度就可以实现相当的模型效果,换来大量的空间节约,加快模型的加载速度和查询速度。
前序要求
请先读取 稀疏参数索引服务Cube单机版使用指南
组件介绍
seq_generator:
此工具用于把Paddle的模型转换成Sequence File,在这里,我给出了两种模式,第一种是普通模式,生成的KV序列当中的Value以未压缩的浮点数来进行保存。第二种是量化模式,生成的KV序列当中的Value按照 [min, max, bytes]来存储。具体原理请参见 (Post-Training 4-bit Quantization on Embedding Tables)
使用方法
在Serving主目录下,到criteo_ctr_with_cube目录下训练出模型
cd Serving/examples/C++/PaddleRec/criteo_ctr_with_cube
python local_train.py # 生成模型接下来可以使用量化和非量化两种方式去生成Sequence File用于Cube稀疏参数索引。
seq_generator ctr_serving_model/SparseFeatFactors ./cube_model/feature # 未量化模式
seq_generator ctr_serving_model/SparseFeatFactors ./cube_model/feature 8 #量化模式此命令会讲ctr_serving_model目录下的稀疏参数文件SparseFeatFactors转换为cube_model目录下的feature文件(Sequence File格式)。目前量化工具仅支持8bit量化,未来将支持压缩率更高和种类更多的量化方法。
用量化模型启动Serving
在Serving当中,使用general_dist_kv_quant_infer op来进行预测时使用量化模型。具体详见 Serving/examples/C++/PaddleRec/criteo_ctr_with_cube/test_server_quant.py。客户端部分不需要做任何改动。
为方便用户做demo,我们给出了从0开始启动量化模型Serving。
cd Serving/examples/C++/PaddleRec/criteo_ctr_with_cube
python local_train.py
cp ../../../build_server/core/predictor/seq_generator seq_generator
cp ../../../build_server/output/bin/cube* ./cube/
sh cube_quant_prepare.sh &
python test_server_quant.py ctr_serving_model_kv &
python test_client.py ctr_client_conf/serving_client_conf.prototxt ./raw_data用户可以将量化后的AUC结果同量化前的AUC做比较
File: doc/Cube_Quant_EN.md
Quantization Storage on Cube Sparse Parameter Indexing
(简体中文|English)
Overview
In our previous article, we know that the sparse parameter is a series of floating-point numbers with large dimensions, and floating-point numbers require 4 Bytes of storage space in the computer. In fact, we don't need very high precision of floating point numbers to achieve a comparable model effect, in exchange for a lot of space savings, speeding up model loading and query speed.
Precondition
Please Read Cube: Sparse Parameter Indexing Service (Local Mode)
Components
seq_generator:
This tool is used to convert the Paddle model into a Sequence File. Here, two modes are given. The first is the normal mode. The value in the generated KV sequence is saved as an uncompressed floating point number. The second is the quantization mode. The Value in the generated KV sequence is stored according to [min, max, bytes]. See the specific principle (Post-Training 4-bit Quantization on Embedding Tables)
Usage
In Serving Directory,train the model in the criteo_ctr_with_cube directory
cd Serving/examples/C++/PaddleRec/criteo_ctr_with_cube
python local_train.py # save modelNext, you can use quantization and non-quantization to generate Sequence File for Cube sparse parameter indexing.
seq_generator ctr_serving_model/SparseFeatFactors ./cube_model/feature # naive mode
seq_generator ctr_serving_model/SparseFeatFactors ./cube_model/feature 8 #quantizationThis command will convert the sparse parameter file SparseFeatFactors in the ctr_serving_model directory into a feature file (Sequence File format) in the cube_model directory. At present, the quantization tool only supports 8-bit quantization. In the future, it will support higher compression rates and more types of quantization methods.
Launch Serving by Quantized Model
In Serving, a quantized model is used when using general_dist_kv_quant_infer op to make predictions. See Serving/examples/C++/PaddleRec/criteo_ctr_with_cube/test_server_quant.py for details. No changes are required on the client side.
In order to make the demo easier for users, the following script is to train the quantized criteo ctr model and launch serving by it.
cd Serving/examples/C++/PaddleRec/criteo_ctr_with_cube
python local_train.py
cp ../../../build_server/core/predictor/seq_generator seq_generator
cp ../../../build_server/output/bin/cube* ./cube/
sh cube_quant_prepare.sh &
python test_server_quant.py ctr_serving_model_kv &
python test_client.py ctr_client_conf/serving_client_conf.prototxt ./raw_dataUsers can compare AUC results after quantization with AUC before quantization.
File: doc/Cube_Test_CN.md
如果获得稀疏参数索引Cube所需的模型输入
背景知识
推荐系统需要大规模稀疏参数索引来帮助分布式部署,可在Serving/examples/C++/PaddleRec/criteo_ctr_with_cube或是PaddleRec了解推荐模型。
稀疏参数索引的模型格式是SequenceFile,源自Hadoop生态的键值对格式文件。
为了方便调试,我们给出了从特定格式的可读文本文件到SequenceFile格式文件的转换工具,以及SequenceFile格式文件与可阅读文字的转换。
用户在调试Cube服务功能时,可以自定义KV对生成SequenceFile格式文件来进行调试。
用户在验证Cube的配送正确性时,可以转换SequenceFile格式文件至可读文字来进行比对验证。
预备知识
- 需要会编译Paddle Serving,参见编译文档
用法
在编译结束后的安装文件,可以得到 seq_reader 和 kv_to_seqfile.py。
生成SequenceFile
在output/tool/下,修改output/tool/source/file.txt,该文件每一行对应一个键值对,用冒号:区分key和value部分。
例如:
1676869128226002114:48241 37064 91 -539 114 51 -122 269 229 -134 -282
1657749292782759014:167 40 98 27 117 10 -29 15 74 67 -54执行
python kv_to_seqfile.py即可生成data文件夹,我们看下它的结构
.
├── 20210805095422
│ └── base
│ └── feature
└── donefile
└── base.txt其中20210805095422/base/feature 就是SequenceFile格式文件,donefile保存在donefile/base.txt。
查看SequenceFile
我们使用seq_reader工具来解读SequenceFile格式文件。
./seq_reader 20210805095422/base/feature 10 # 阅读开头的10个KV对
./seq_reader 20210805095422/base/feature # 阅读所有KV对结果
key: 1676869128226002114 , value: 343832343109333730363409093931092D35333909313134093531092D3132320932363909323239092D313334092D323832
key: 1657749292782759014 , value: 3136370934300909393809323709313137093130092D3239093135093734093637092D3534其中value 我们目前都以16进制的形式打印。
File: doc/Docker_Images_CN.md
[Binary file]
File: doc/Docker_Images_EN.md
Docker Images
(简体中文|English)
This document maintains a list of docker images provided by Paddle Serving.
Get docker image
You can get images in two ways:
Pull image directly from dockerhub or
registry.baidubce.comthrough TAG:shelldocker pull registry.baidubce.com/paddlepaddle/serving:<TAG>Building image based on dockerfile
Create a new folder and copy Dockerfile to this folder, and run the following command:
shelldocker build -f tools/${DOCKERFILE} -t registry.baidubce.com/paddlepaddle/serving:<images-tag> .
Image description
If you want to customize your Serving based on source code, use the version with the suffix - devel.
If you need to develop and compile based on the source code, please use the version with the suffix -devel.
In the TAG column, 0.9.0 can also be replaced with the corresponding version number, such as 0.5.0/0.4.1, etc., but it should be noted that some development environments only increase with a certain version iteration, so not all environments All have the corresponding version number can be used.
Development Docker Images:
A variety of development tools are installed in the development image, which can be used to debug and compile code, and adapt to two GCC versions and multiple CUDA environments, but the image size is large.
| Description | OS | TAG | Dockerfile |
|---|---|---|---|
| CPU development | Ubuntu16 | 0.9.0-devel | Dockerfile.devel |
| GPU (cuda10.1-cudnn7-tensorRT6) development | Ubuntu16 | 0.9.0-cuda10.1-cudnn7-devel | Dockerfile.cuda10.1-cudnn7.devel |
| GPU (cuda10.2-cudnn7-tensorRT6) development | Ubuntu16 | 0.9.0-cuda10.2-cudnn7-devel | Dockerfile.cuda10.2-cudnn7.devel |
| GPU (cuda10.2-cudnn8-tensorRT7) development | Ubuntu16 | 0.9.0-cuda10.2-cudnn8-devel | Dockerfile.cuda10.2-cudnn8.devel |
| GPU (cuda11.2-cudnn8-tensorRT8) development | Ubuntu16 | 0.9.0-cuda11.2-cudnn8-devel | Dockerfile.cuda11.2-cudnn8.devel |
Runtime Docker Images:
Runtime Docker Images is lighter than Develop Images, and Running Images are made up with serving whl and bin, but without develop tools like cmake because of lower image size. If you want to know about it, plese check the document Paddle Serving on Kubernetes.
| Env | Version | Docker images tag | OS | Gcc Version | Size |
|---|---|---|---|---|---|
| CPU | 0.9.0 | 0.9.0-runtime | Ubuntu 16 | 8.2.0 | 3.9 GB |
| CUDA 10.1 + cuDNN 7 | 0.9.0 | 0.9.0-cuda10.1-cudnn7-runtime | Ubuntu 16 | 8.2.0 | 10 GB |
| CUDA 10.2 + cuDNN 7 | 0.9.0 | 0.9.0-cuda10.2-cudnn7-runtime | Ubuntu 16 | 8.2.0 | 10.1 GB |
| CUDA 10.2 + cuDNN 8 | 0.9.0 | 0.9.0-cuda10.2-cudnn8-runtime | Ubuntu 16 | 8.2.0 | 10.1 |
| CUDA 11.2 + cuDNN 8 | 0.9.0 | 0.9.0-cuda11.2-cudnn8-runtime | Ubuntu 16 | 8.2.0 | 14.2 GB |
Java SDK Docker Image:
registry.baidubce.com/paddlepaddle/serving:0.9.0-cuda10.2-cudnn8-javaXPU Docker Images:
registry.baidubce.com/paddlepaddle/serving:xpu-arm # for arm xpu user
registry.baidubce.com/paddlepaddle/serving:xpu-x86 # for x86 xpu userRequirements for running CUDA containers
Running a CUDA container requires a machine with at least one CUDA-capable GPU and a driver compatible with the CUDA toolkit version you are using.
The machine running the CUDA container only requires the NVIDIA driver, the CUDA toolkit does not have to be installed.
For the relationship between CUDA toolkit version, Driver version and GPU architecture, please refer to nvidia-docker wiki.
File: doc/FAQ_CN.md
[Binary file]
File: doc/Imdb_GO_Client_CN.md
[Binary file]
File: doc/Imdb_GO_Client_EN.md
How to use Go Client of Paddle Serving
(简体中文|English)
This document shows how to use Go as your client language. For Go client in Paddle Serving, a simple client package is provided https://github.com/PaddlePaddle/Serving/tree/develop/go/serving_client, a user can import this package as needed. Here is a simple example of sentiment analysis task based on IMDB dataset.
Install
We suppose you have 1.9.2 or later version installed and python 2.7 version installed
go get github.com/PaddlePaddle/Serving/go/serving_client
go get github.com/PaddlePaddle/Serving/go/proto
pip install paddle-serving-serverDownload Text Classification Model
wget https://paddle-serving.bj.bcebos.com/data/text_classification/imdb_serving_example.tar.gz
tar -xzf imdb_serving_example.tar.gzStart Server
python -m paddle_serving_server.serve --model ./serving_server_model/ --port 9292Client code example
// imdb_client.go
package main
import (
"io"
"fmt"
"strings"
"bufio"
"strconv"
"os"
serving_client "github.com/PaddlePaddle/Serving/go/serving_client"
)
func main() {
var config_file_path string
config_file_path = os.Args[1]
handle := serving_client.LoadModelConfig(config_file_path)
handle = serving_client.Connect("127.0.0.1", "9292", handle)
test_file_path := os.Args[2]
fi, err := os.Open(test_file_path)
if err != nil {
fmt.Print(err)
}
defer fi.Close()
br := bufio.NewReader(fi)
fetch := []string{"cost", "acc", "prediction"}
var result map[string][]float32
for {
line, err := br.ReadString('\n')
if err == io.EOF {
break
}
line = strings.Trim(line, "\n")
var words = []int64{}
s := strings.Split(line, " ")
value, err := strconv.Atoi(s[0])
var feed_int_map map[string][]int64
for _, v := range s[1:value + 1] {
int_v, _ := strconv.Atoi(v)
words = append(words, int64(int_v))
}
label, err := strconv.Atoi(s[len(s)-1])
if err != nil {
panic(err)
}
feed_int_map = map[string][]int64{}
feed_int_map["words"] = words
feed_int_map["label"] = []int64{int64(label)}
result = serving_client.Predict(handle, feed_int_map, fetch)
fmt.Println(result["prediction"][1], "\t", int64(label))
}
}Prediction based on IMDB Test set
go run imdb_client.go serving_client_conf/serving_client_conf.stream.prototxt test.data > resultCompute accuracy
// acc.go
package main
import (
"io"
"os"
"fmt"
"bufio"
"strings"
"strconv"
)
func main() {
score_file := os.Args[1]
fi, err := os.Open(score_file)
if err != nil {
fmt.Print(err)
}
defer fi.Close()
br := bufio.NewReader(fi)
total := int(0)
acc := int(0)
for {
line, err := br.ReadString('\n')
if err == io.EOF {
break
}
line = strings.Trim(line, "\n")
s := strings.Split(line, "\t")
prob_str := strings.Trim(s[0], " ")
label_str := strings.Trim(s[1], " ")
prob, err := strconv.ParseFloat(prob_str, 32)
if err != nil {
panic(err)
}
label, err := strconv.ParseFloat(label_str, 32)
if err != nil {
panic(err)
}
if (prob - 0.5) * (label - 0.5) > 0 {
acc++
}
total++
}
fmt.Println("total num: ", total)
fmt.Println("acc num: ", acc)
fmt.Println("acc: ", float32(acc) / float32(total))
}go run acc.go result
total num: 25000
acc num: 22014
acc: 0.88056File: doc/index.rst
:github_url: https://github.com/PaddlePaddle/Serving
.. mdinclude:: md/logo.md
Paddle Serving
.. toctree::
:maxdepth: 1
:caption: Readme
:hidden:
.. _instruction: instruction.html
File: doc/Install_CN.md
使用Docker安装Paddle Serving
(简体中文|English)
强烈建议您在Docker内构建Paddle Serving,更多镜像请查看Docker镜像列表。
提示-1:本项目仅支持Python3.6/3.7/3.8/3.9,接下来所有的与Python/Pip相关的操作都需要选择正确的Python版本。
提示-2:以下示例中GPU环境均为cuda11.2-cudnn8,如果您使用Python Pipeline来部署,并需要Nvidia TensorRT来优化预测性能,请参考以下说明来选择其他版本。
1.使用开发镜像
- Serving 镜像: registry.baidubce.com/paddlepaddle/serving:{Tag}
- Paddle 镜像: registry.baidubce.com/paddlepaddle/paddle:{Tag}
同时支持使用 Serving 镜像和 Paddle 镜像,1.1 和 1.2 章节中的操作2选1即可。 在Paddle docker镜像上部署 Servin g服务需要安装额外依赖库,因此,我们直接使用 Serving 开发镜像。
| 环境 | Serving镜像 Tag | 操作系统 | Paddle镜像 Tag | 操作系统 |
|---|---|---|---|---|
| CPU | 0.9.0-devel | Ubuntu 16 | 2.3.0 | Ubuntu 18 |
| CUDA10.1 + cuDNN 7 | 0.9.0-cuda10.1-cudnn7-devel | Ubuntu 16 | 无 | 无 |
| CUDA10.2 + cuDNN 7 | 0.9.0-cuda10.2-cudnn7-devel | Ubuntu 16 | 2.3.0-gpu-cuda10.2-cudnn7 | Ubuntu 18 |
| CUDA10.2 + cuDNN 8 | 0.9.0-cuda10.2-cudnn8-devel | Ubuntu 16 | 无 | Ubuntu 18 |
| CUDA11.2 + cuDNN 8 | 0.9.0-cuda11.2-cudnn8-devel | Ubuntu 16 | 2.3.0-gpu-cuda11.2-cudnn8 | Ubuntu 18 |
| ARM + XPU | xpu-arm | CentOS 8.3 | 无 | 无 |
对于Windows 10 用户,请参考文档Windows平台使用Paddle Serving指导。
1.1 Serving开发镜像(CPU/GPU 2选1)
CPU:
# 启动 CPU Docker
docker pull registry.baidubce.com/paddlepaddle/serving:0.9.0-devel
docker run -p 9292:9292 --name test_cpu -dit registry.baidubce.com/paddlepaddle/serving:0.9.0-devel bash
docker exec -it test_cpu bash
git clone https://github.com/PaddlePaddle/ServingGPU:
# 启动 GPU Docker
docker pull registry.baidubce.com/paddlepaddle/serving:0.9.0-cuda11.2-cudnn8-devel
nvidia-docker run -p 9292:9292 --name test_gpu -dit registry.baidubce.com/paddlepaddle/serving:0.9.0-cuda11.2-cudnn8-devel bash
nvidia-docker exec -it test_gpu bash
git clone https://github.com/PaddlePaddle/Serving**ARM & XPU: **
docker pull registry.baidubce.com/paddlepaddle/serving:xpu-arm
docker run -p 9292:9292 --name test_arm_xpu -dit registry.baidubce.com/paddlepaddle/serving:xpu-arm bash
docker exec -it test_arm_xpu bash
git clone https://github.com/PaddlePaddle/Serving1.2 Paddle开发镜像(CPU/GPU 2选1)
CPU:
### 启动 CPU Docker
nvidia-docker pull registry.baidubce.com/paddlepaddle/paddle:2.3.0
docker run -p 9292:9292 --name test -dit registry.baidubce.com/paddlepaddle/paddle:2.3.0 bash
docker exec -it test bash
git clone https://github.com/PaddlePaddle/Serving
### Paddle开发镜像需要执行以下脚本增加Serving所需依赖项
bash Serving/tools/paddle_env_install.shGPU:
### 启动 GPU Docker
nvidia-docker pull registry.baidubce.com/paddlepaddle/paddle:2.3.0-gpu-cuda11.2-cudnn8
nvidia-docker run -p 9292:9292 --name test -dit registry.baidubce.com/paddlepaddle/paddle:2.3.0-gpu-cuda11.2-cudnn8 bash
nvidia-docker exec -it test bash
git clone https://github.com/PaddlePaddle/Serving
### Paddle开发镜像需要执行以下脚本增加Serving所需依赖项
bash Serving/tools/paddle_env_install.sh2.安装 Wheel 包
安装所需的pip依赖
cd Serving
pip3 install -r python/requirements.txt安装服务whl包,共有3种client、app、server,Server分为CPU和GPU,GPU包根据您的环境选择一种安装
- post112 = CUDA11.2 + cuDNN8 + TensorRT8(推荐)
- post101 = CUDA10.1 + cuDNN7 + TensorRT6
- post102 = CUDA10.2 + cuDNN7 + TensorRT6 (与Paddle 镜像一致)
- post1028 = CUDA10.2 + cuDNN8 + TensorRT7
2.1 在线安装
在线安装采用 pypi 下载并安装的方式。
pip3 install paddle-serving-client==0.9.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip3 install paddle-serving-app==0.9.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
# CPU Server
pip3 install paddle-serving-server==0.9.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
# GPU Server,需要确认环境再选择执行哪一条,推荐使用CUDA 11.2的包
pip3 install paddle-serving-server-gpu==0.9.0.post112 -i https://pypi.tuna.tsinghua.edu.cn/simple默认开启国内清华镜像源来加速下载,如果您使用HTTP代理可以关闭(-i https://pypi.tuna.tsinghua.edu.cn/simple)
如果需要使用develop分支编译的安装包,请从下载Wheel包中获取下载地址进行下载,使用pip install命令进行安装。如果您想自行编译,请参照Paddle Serving编译文档。
paddle-serving-server 和 paddle-serving-server-gpu 安装包支持Centos 6/7, Ubuntu 16/18和Windows 10。
paddle-serving-client 和 paddle-serving-app 安装包支持 Linux 和 Windows,其中 paddle-serving-client 仅支持 python3.6/3.7/3.8/3.9。
当您使用paddle_serving_client.convert命令或者Python Pipeline框架时才需要安装。
# CPU环境请执行
pip3 install paddlepaddle==2.3.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
# GPU CUDA 11.2环境请执行
pip3 install paddlepaddle-gpu==2.3.0.post112 -i https://pypi.tuna.tsinghua.edu.cn/simple注意: 其他版本请参考Paddle-Inference官方文档-下载安装Linux预测库 选择相应的GPU环境的 URL 链接并进行安装。
# CUDA11.2 + CUDNN8 + TensorRT8 + Python(3.6-3.9)
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda11.2_cudnn8.2.1_trt8.0.3.4/paddlepaddle_gpu-2.3.0.post112-cp36-cp36m-linux_x86_64.whl
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda11.2_cudnn8.2.1_trt8.0.3.4/paddlepaddle_gpu-2.3.0.post112-cp37-cp37m-linux_x86_64.whl
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda11.2_cudnn8.2.1_trt8.0.3.4/paddlepaddle_gpu-2.3.0.post112-cp38-cp38-linux_x86_64.whl
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda11.2_cudnn8.2.1_trt8.0.3.4/paddlepaddle_gpu-2.3.0.post112-cp39-cp39-linux_x86_64.whl
# CUDA10.1 + CUDNN7 + TensorRT6 + Python(3.6-3.9)
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda10.1_cudnn7.6.5_trt6.0.1.5/paddlepaddle_gpu-2.3.0.post101-cp36-cp36m-linux_x86_64.whl
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda10.1_cudnn7.6.5_trt6.0.1.5/paddlepaddle_gpu-2.3.0.post101-cp37-cp37m-linux_x86_64.whl
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda10.1_cudnn7.6.5_trt6.0.1.5/paddlepaddle_gpu-2.3.0.post101-cp38-cp38-linux_x86_64.whl
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda10.1_cudnn7.6.5_trt6.0.1.5/paddlepaddle_gpu-2.3.0.post101-cp39-cp39-linux_x86_64.whl
# CUDA10.2 + CUDNN8 + TensorRT7 + Python(3.6-3.9)
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda10.2_cudnn8.1.1_trt7.2.3.4/paddlepaddle_gpu-2.3.0-cp36-cp36m-linux_x86_64.whl
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda10.2_cudnn8.1.1_trt7.2.3.4/paddlepaddle_gpu-2.3.0-cp37-cp37m-linux_x86_64.whl
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda10.2_cudnn8.1.1_trt7.2.3.4/paddlepaddle_gpu-2.3.0-cp38-cp38-linux_x86_64.whl
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda10.2_cudnn8.1.1_trt7.2.3.4/paddlepaddle_gpu-2.3.0-cp39-cp39-linux_x86_64.whl2.2 离线安装
离线安装是指所有的 Paddle 和 Serving 包和依赖库,传入到无网或弱网环境下安装。
1.安装离线 Wheel 包
Serving 和 Paddle Wheel包的离线依赖包下载有4个链接。
wget https://paddle-serving.bj.bcebos.com/offline_wheels/0.9.0/py36_offline_whl_packages.tar
wget https://paddle-serving.bj.bcebos.com/offline_wheels/0.9.0/py37_offline_whl_packages.tar
wget https://paddle-serving.bj.bcebos.com/offline_wheels/0.9.0/py38_offline_whl_packages.tar
wget https://paddle-serving.bj.bcebos.com/offline_wheels/0.9.0/py39_offline_whl_packages.tar通过运行 install.py 脚本可本地安装 Serving 和 Paddle Wheel 包。install.py 脚本的参数列表如下:
python3 install.py
--python_version : Python version for installing wheels, one of [py36, py37, py38, py39], py37 default.
--device : Type of devices, one of [cpu, gpu], cpu default.
--cuda_version : CUDA version for GPU, one of [101, 102, 112, empty], empty default.
--serving_version : Verson of Serving, one of [0.9.0, no_install], 0.9.0 default.
--paddle_version Verson of Paddle, one of [2.3.0, no_install], 2.3.0 default.2.在环境变量中指定 SERVING_BIN 路径
完成第1步安装后,若仅使用 python pipeline 模式可忽略此步骤。
如使用 C++ Serving 使用命令行方式启动服务,示例如下。则需要在命令行窗口或服务启动程序中导出环境变量 SERVING_BIN,使用本地的 serving 二进制程序运行服务。
C++ Serving 命令行启动服务示例:
python3 -m paddle_serving_server.serve --model serving_model --thread 10 --port 9292 --gpu_ids 0,1,2由于所有版本的二进制程序包有 20 GB,非常大。因此提供多个版本的下载链接,通过手动 wget 下载指定版本到 serving_bin 目录下,解压后导出到环境变量中。
- cpu-avx-mkl: https://paddle-serving.bj.bcebos.com/test-dev/bin/serving-cpu-avx-mkl-0.9.0.tar.gz
- cpu-avx-openblas: https://paddle-serving.bj.bcebos.com/test-dev/bin/serving-cpu-avx-openblas-0.9.0.tar.gz
- cpu-noavx-openblas: https://paddle-serving.bj.bcebos.com/test-dev/bin/serving-cpu-noavx-openblas-0.9.0.tar.gz
- cuda10.1-cudnn7-TensorRT6: https://paddle-serving.bj.bcebos.com/test-dev/bin/serving-gpu-101-0.9.0.tar.gz
- cuda10.2-cudnn7-TensorRT6: https://paddle-serving.bj.bcebos.com/test-dev/bin/serving-gpu-102-0.9.0.tar.gz
- cuda10.2-cudnn8-TensorRT7: https://paddle-serving.bj.bcebos.com/test-dev/bin/serving-gpu-1028-0.9.0.tar.gz
- cuda11.2-cudnn8-TensorRT8: https://paddle-serving.bj.bcebos.com/test-dev/bin/serving-gpu-112-0.9.0.tar.gz
以 GPU CUDA 10.2 为例,在命令行或启动程序中设置环境变量如下:
export SERVING_BIN = $PWD/serving_bin/serving-gpu-102-0.9.0/serving3.运行 install.py 安装 Wheel 包
1.同时安装 Serving 和 Paddle 的 py38 版本 GPU wheel 包:
python3 install.py --cuda_version="102" --python_version="py38" --device="GPU" --serving_version="0.9.0" --paddle_version="2.3.0"2.仅安装 Serving 的 py39 版本 CPU wheel 包,设置 --paddle_version="no_install" 表示不安装 Paddle 预测库,设置 --device="cpu" 表示 cpu 版本
python3 install.py --cuda_version="" --python_version="py39" --device="cpu" --serving_version="0.9.0" --paddle_version="no_install"3.仅安装 Paddle 的 py36 版本cuda=11.2 的 GPU wheel 包,
python3 install.py --cuda_version="112" --python_version="py36" --device="GPU" --serving_version="no_install" --paddle_version="2.3.0"2.3 ARM & XPU 安装 wheel 包
由于使用 ARM 和 XPU 的用户较少,安装此环境的 Wheel 单独提供如下,其中 paddle_serving_client 仅提供 py36 的版本,如需其他版本请与我们联系。
pip3.6 install https://paddle-serving.bj.bcebos.com/test-dev/whl/arm/paddle_serving_app-0.9.0-py3-none-any.whl
pip3.6 install https://paddle-serving.bj.bcebos.com/test-dev/whl/arm/paddle_serving_client-0.9.0-cp36-none-any.whl
pip3.6 install https://paddle-serving.bj.bcebos.com/test-dev/whl/arm/paddle_serving_server_xpu-0.9.0.post2-py3-none-any.whl二进制包地址:
wget https://paddle-serving.bj.bcebos.com/test-dev/bin/serving-xpu-aarch64-0.9.0.tar.gz3.环境检查
当以上步骤均完成后可使用命令行运行环境检查功能,自动运行Paddle Serving相关示例,进行环境相关配置校验。
python3 -m paddle_serving_server.serve check详情请参考环境检查文档
File: doc/Install_EN.md
Install Paddle Serving with Docker
(简体中文|English)
Strongly recommend you build Paddle Serving in Docker. For more images, please refer to Docker Image List.
Tip-1: This project only supports Python3.6/3.7/3.8/3.9, all subsequent operations related to Python/Pip need to select the correct Python version.
Tip-2: The GPU environments in the following examples are all cuda11.2-cudnn8. If you use Python Pipeline to deploy and need Nvidia TensorRT to optimize prediction performance, please refer to Supported Mirroring Environment and Instructions to choose other versions.
1.Use devel docker
Both Serving Dev Image and Paddle Dev Image are supported at the same time. You can choose 1 from the operation 2 in chapters 1.1 and 1.2.Deploying the Serving service on the Paddle docker image requires the installation of additional dependency libraries. Therefore, we directly use the Serving development image.
| Environment | Serving Development Image Tag | Operating System | Paddle Development Image Tag | Operating System |
|---|---|---|---|---|
| CPU | 0.9.0-devel | Ubuntu 16 | 2.3.0 | Ubuntu 18 |
| CUDA10.1 + cuDNN 7 | 0.9.0-cuda10.1-cudnn7-devel | Ubuntu 16 | None | None |
| CUDA10.2 + cuDNN 7 | 0.9.0-cuda10.2-cudnn7-devel | Ubuntu 16 | 2.3.0-gpu-cuda10.2-cudnn7 | Ubuntu 18 |
| CUDA10.2 + cuDNN 8 | 0.9.0-cuda10.2-cudnn8-devel | Ubuntu 16 | None | None |
| CUDA11.2 + cuDNN 8 | 0.9.0-cuda11.2-cudnn8-devel | Ubuntu 16 | 2.3.0-gpu-cuda11.2-cudnn8 | Ubuntu 18 |
| ARM + XPU | xpu-arm | CentOS 8.3 | None | None |
For Windows 10 users, please refer to the document Paddle Serving Guide for Windows Platform.
1.1 Serving Devel Images (CPU/GPU 2 choose 1)
CPU:
# Start CPU Docker Container
docker pull registry.baidubce.com/paddlepaddle/serving:0.9.0-devel
docker run -p 9292:9292 --name test_cpu -dit registry.baidubce.com/paddlepaddle/serving:0.9.0-devel bash
docker exec -it test_cpu bash
git clone https://github.com/PaddlePaddle/ServingGPU:
# Start GPU Docker Container
docker pull registry.baidubce.com/paddlepaddle/serving:0.9.0-cuda11.2-cudnn7-devel
nvidia-docker run -p 9292:9292 --name test_gpu -dit docker pull registry.baidubce.com/paddlepaddle/serving:0.9.0-cuda11.2-cudnn7-devel bash
nvidia-docker exec -it test_gpu bash
git clone https://github.com/PaddlePaddle/Serving**ARM & XPU: **
docker pull registry.baidubce.com/paddlepaddle/serving:xpu-arm
docker run -p 9292:9292 --name test_arm_xpu -dit registry.baidubce.com/paddlepaddle/serving:xpu-arm bash
docker exec -it test_arm_xpu bash
git clone https://github.com/PaddlePaddle/Serving1.2 Paddle Devel Images (choose any codeblock of CPU/GPU)
CPU:
# Start CPU Docker Container
docker pull registry.baidubce.com/paddlepaddle/paddle:2.3.0
docker run -p 9292:9292 --name test_cpu -dit registry.baidubce.com/paddlepaddle/paddle:2.3.0 bash
docker exec -it test_cpu bash
git clone https://github.com/PaddlePaddle/Serving
### Paddle dev image needs to run the following script to increase the dependencies required by Serving
bash Serving/tools/paddle_env_install.shGPU:
### Start GPU Docker
nvidia-docker pull registry.baidubce.com/paddlepaddle/paddle:2.3.0-gpu-cuda11.2-cudnn8
nvidia-docker run -p 9292:9292 --name test_gpu -dit registry.baidubce.com/paddlepaddle/paddle:2.3.0-gpu-cuda11.2-cudnn8 bash
nvidia-docker exec -it test_gpu bash
git clone https://github.com/PaddlePaddle/Serving
### Paddle development image needs to execute the following script to increase the dependencies required by Serving
bash Serving/tools/paddle_env_install.sh2. Install wheel packages
Install the required pip dependencies
cd Serving
pip3 install -r python/requirements.txtInstall the service whl package. There are three types of client, app and server. The server is divided into CPU and GPU. Choose one installation according to the environment.
- post112 = CUDA11.2 + cuDNN8 + TensorRT8(Recommanded)
- post101 = CUDA10.1 + cuDNN7 + TensorRT6
- post102 = CUDA10.2 + cuDNN7 + TensorRT6 (The same with paddle docker images)
- post1028 = CUDA10.2 + cuDNN8 + TensorRT7
2.1 Online Install
Online installation uses pypi to download and install.
pip3 install paddle-serving-client==0.9.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip3 install paddle-serving-app==0.9.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
# CPU Server
pip3 install paddle-serving-server==0.9.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
# GPU environments need to confirm the environment before choosing which one to execute
pip3 install paddle-serving-server-gpu==0.9.0.post112 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip3 install paddle-serving-server-gpu==0.9.0.post102 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip3 install paddle-serving-server-gpu==0.9.0.post101 -i https://pypi.tuna.tsinghua.edu.cn/simpleBy default, the domestic Tsinghua mirror source is turned on to speed up the download. If you use a proxy, you can turn it off(-i https://pypi.tuna.tsinghua.edu.cn/simple).
If you need to use the installation package compiled by the develop branch, please download the download address from Download wheel packages, and use the pip install command to install. If you want to compile by yourself, please refer to Paddle Serving Compilation Document.
The paddle-serving-server and paddle-serving-server-gpu installation packages support Centos 6/7, Ubuntu 16/18 and Windows 10.
The paddle-serving-client and paddle-serving-app installation packages support Linux and Windows, and paddle-serving-client only supports python3.6/3.7/3.8/3.9.
**You only need to install it when you use the paddle_serving_client.convert command or the Python Pipeline framework. **
# CPU environment please execute
pip3 install paddlepaddle==2.3.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
# GPU CUDA 11.2 environment please execute
pip3 install paddlepaddle-gpu==2.3.0.post112 -i https://pypi.tuna.tsinghua.edu.cn/simpleNote: If you want to use other versions, please do not execute the above commands directly, you need to refer to Paddle-Inference official document-download and install the Linux prediction library Select the URL link of the corresponding GPU environment and install it. Assuming that you use Python3.6, please follow the codeblock.
# CUDA11.2 + CUDNN8 + TensorRT8 + Python(3.6-3.9)
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda11.2_cudnn8.2.1_trt8.0.3.4/paddlepaddle_gpu-2.3.0.post112-cp36-cp36m-linux_x86_64.whl
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda11.2_cudnn8.2.1_trt8.0.3.4/paddlepaddle_gpu-2.3.0.post112-cp37-cp37m-linux_x86_64.whl
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda11.2_cudnn8.2.1_trt8.0.3.4/paddlepaddle_gpu-2.3.0.post112-cp38-cp38-linux_x86_64.whl
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda11.2_cudnn8.2.1_trt8.0.3.4/paddlepaddle_gpu-2.3.0.post112-cp39-cp39-linux_x86_64.whl
# CUDA10.1 + CUDNN7 + TensorRT6 + Python(3.6-3.9)
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda10.1_cudnn7.6.5_trt6.0.1.5/paddlepaddle_gpu-2.3.0.post101-cp36-cp36m-linux_x86_64.whl
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda10.1_cudnn7.6.5_trt6.0.1.5/paddlepaddle_gpu-2.3.0.post101-cp37-cp37m-linux_x86_64.whl
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda10.1_cudnn7.6.5_trt6.0.1.5/paddlepaddle_gpu-2.3.0.post101-cp38-cp38-linux_x86_64.whl
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda10.1_cudnn7.6.5_trt6.0.1.5/paddlepaddle_gpu-2.3.0.post101-cp39-cp39-linux_x86_64.whl
# CUDA10.2 + CUDNN8 + TensorRT7 + Python(3.6-3.9)
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda10.2_cudnn8.1.1_trt7.2.3.4/paddlepaddle_gpu-2.3.0-cp36-cp36m-linux_x86_64.whl
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda10.2_cudnn8.1.1_trt7.2.3.4/paddlepaddle_gpu-2.3.0-cp37-cp37m-linux_x86_64.whl
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda10.2_cudnn8.1.1_trt7.2.3.4/paddlepaddle_gpu-2.3.0-cp38-cp38-linux_x86_64.whl
pip3 install https://paddle-inference-lib.bj.bcebos.com/2.3.0/python/Linux/GPU/x86-64_gcc8.2_avx_mkl_cuda10.2_cudnn8.1.1_trt7.2.3.4/paddlepaddle_gpu-2.3.0-cp39-cp39-linux_x86_64.whl2.2 Offline Install
Offline installation is to download all Paddle and Serving packages and dependent libraries, and install them in a no-network or weak-network environment.
1.Install offline wheel packages
The independent dependencies of the Serving and Paddle Wheel packages are downloaded by four links.
wget https://paddle-serving.bj.bcebos.com/offline_wheels/0.9.0/py36_offline_whl_packages.tar
wget https://paddle-serving.bj.bcebos.com/offline_wheels/0.9.0/py37_offline_whl_packages.tar
wget https://paddle-serving.bj.bcebos.com/offline_wheels/0.9.0/py38_offline_whl_packages.tar
wget https://paddle-serving.bj.bcebos.com/offline_wheels/0.9.0/py39_offline_whl_packages.tarThe Serving and Paddle Wheel packages can be installed locally by running the install.py script. The parameter list for the install.py script is as follows:
python3 install.py
--python_version : Python version for installing wheels, one of [py36, py37, py38, py39], py37 default.
--device : Type of devices, one of [cpu, gpu], cpu default.
--cuda_version : CUDA version for GPU, one of [101, 102, 112, empty], empty default.
--serving_version : Verson of Serving, one of [0.9.0, no_install], 0.9.0 default.
--paddle_version Verson of Paddle, one of [2.3.0, no_install], 2.3.0 default.2.Specify the SERVING_BIN path in the environment variable
After completing step 1 of the installation, you can ignore this step if you only use the python pipeline mode.
If you use C++ Serving to start the service using the command line, the example is as follows. Then you need to export the environment variable SERVING_BIN in the command line window or service launcher, and use the local serving binary to run the service.
C++ Serving command line start service example:
python3 -m paddle_serving_server.serve --model serving_model --thread 10 --port 9292 --gpu_ids 0,1,2Since the binary package for all versions has 20 GB, it is very large. Therefore, multiple versions of download links are provided. Manually wget downloads the specified version to the serving_bin directory, decompresses it and exports it to the environment variable.
- cpu-avx-mkl: https://paddle-serving.bj.bcebos.com/test-dev/bin/serving-cpu-avx-mkl-0.9.0.tar.gz
- cpu-avx-openblas: https://paddle-serving.bj.bcebos.com/test-dev/bin/serving-cpu-avx-openblas-0.9.0.tar.gz
- cpu-noavx-openblas: https://paddle-serving.bj.bcebos.com/test-dev/bin/serving-cpu-noavx-openblas-0.9.0.tar.gz
- cuda10.1-cudnn7-TensorRT6: https://paddle-serving.bj.bcebos.com/test-dev/bin/serving-gpu-101-0.9.0.tar.gz
- cuda10.2-cudnn7-TensorRT6: https://paddle-serving.bj.bcebos.com/test-dev/bin/serving-gpu-102-0.9.0.tar.gz
- cuda10.2-cudnn8-TensorRT7: https://paddle-serving.bj.bcebos.com/test-dev/bin/serving-gpu-1028-0.9.0.tar.gz
- cuda11.2-cudnn8-TensorRT8: https://paddle-serving.bj.bcebos.com/test-dev/bin/serving-gpu-112-0.9.0.tar.gz
Taking GPU CUDA 10.2 as an example, set the environment variables on the command line or in the launcher as follows:
3.Run install.py to install wheel packages
- Install the py38 version GPU wheel package of Serving and Paddle at the same time:
python3 install.py --cuda_version="102" --python_version="py38" --device="GPU" --serving_version="0.9.0" --paddle_version="2.3.0"2.Only install the py39 version of the Serving CPU wheel package, set --paddle_version="no_install" to not install the Paddle prediction library, set --device="cpu" to indicate the cpu version
python3 install.py --cuda_version="" --python_version="py39" --device="cpu" --serving_version="0.9.0" --paddle_version="no_install"- Install only the GPU wheel package of Paddle's py36 version
cuda=11.2
python3 install.py --cuda_version="112" --python_version="py36" --device="GPU" --serving_version="no_install" --paddle_version="2.3.0"2.3 ARM & XPU Install
Since there are few users using ARM and XPU, the Wheel for installing this environment is provided separately as follows, among which paddle_serving_client only provides the py36 version, if you need other versions, please contact us.
pip3.6 install https://paddle-serving.bj.bcebos.com/test-dev/whl/arm/paddle_serving_app-0.9.0-py3-none-any.whl
pip3.6 install https://paddle-serving.bj.bcebos.com/test-dev/whl/arm/paddle_serving_client-0.9.0-cp36-none-any.whl
pip3.6 install https://paddle-serving.bj.bcebos.com/test-dev/whl/arm/paddle_serving_server_xpu-0.9.0.post2-py3-none-any.whlDownload binary package address:
wget https://paddle-serving.bj.bcebos.com/test-dev/bin/serving-xpu-aarch64-0.9.0.tar.gz3.Installation Check
When the above steps are completed, you can use the command line to run the environment check function to automatically run the Paddle Serving related examples to verify the environment-related configuration.
python3 -m paddle_serving_server.serve checkFor more information, please seeInstallation Check
File: doc/Install_Linux_Env_CN.md
原生系统标准环境安装
本文介绍基于原生系统标准环境进行配置安装。
CentOS 7 环境配置(第一步)
一.环境准备
- Python 版本 3.6/3.7/3.8/3.9 (64 bit)
二.选择 CPU/GPU
如果您的计算机有 NVIDIA® GPU,请确保满足以下条件
三.安装必要工具
需要安装的依赖库及工具详见下表:
| 组件 | 版本要求 |
|---|---|
| bzip2-devel | 1.0.6 and later |
| make | later |
| gcc | 8.2.0 |
| gcc-c++ | 8.2.0 |
| cmake | 3.15.0 and later |
| Go | 1.17.2 and later |
| openssl-devel | 1.0.2k |
| patchelf | 0.9 |
更新系统源
更新
yum的源:textyum update并添加必要的yum源:
textyum install -y epel-release安装工具
bzip2以及make:textyum install -y bzip2textyum install -y makecmake 需要3.15以上,建议使用3.16.0:
textwget -q https://cmake.org/files/v3.16/cmake-3.16.0-Linux-x86_64.tar.gztexttar -zxvf cmake-3.16.0-Linux-x86_64.tar.gztextrm cmake-3.16.0-Linux-x86_64.tar.gztextPATH=/home/cmake-3.16.0-Linux-x86_64/bin:$PATHgcc 需要5.4以上,建议使用8.2.0:
textwget -q https://paddle-docker-tar.bj.bcebos.com/home/users/tianshuo/bce-python-sdk-0.8.27/gcc-8.2.0.tar.xz && \ tar -xvf gcc-8.2.0.tar.xz && \ cd gcc-8.2.0 && \ sed -i 's#ftp://gcc.gnu.org/pub/gcc/infrastructure/#https://paddle-ci.gz.bcebos.com/#g' ./contrib/download_prerequisites && \ unset LIBRARY_PATH CPATH C_INCLUDE_PATH PKG_CONFIG_PATH CPLUS_INCLUDE_PATH INCLUDE && \ ./contrib/download_prerequisites && \ cd .. && mkdir temp_gcc82 && cd temp_gcc82 && \ ../gcc-8.2.0/configure --prefix=/usr/local/gcc-8.2 --enable-threads=posix --disable-checking --disable-multilib && \ make -j8 && make install安装GOLANG
建议使用 go1.17.2:
textwget -qO- https://go.dev/dl/go1.17.2.linux-amd64.tar.gz | \ tar -xz -C /usr/local && \ mkdir /root/go && \ mkdir /root/go/bin && \ mkdir /root/go/src && \ echo "GOROOT=/usr/local/go" >> /root/.bashrc && \ echo "GOPATH=/root/go" >> /root/.bashrc && \ echo "PATH=/usr/local/go/bin:/root/go/bin:$PATH" >> /root/.bashrc source /root/.bashrc安装依赖库
安装相关依赖库 patchelf:
textyum install patchelf配置 ssl 依赖库
textwget https://paddle-serving.bj.bcebos.com/others/centos_ssl.tar && \ tar xf centos_ssl.tar && rm -rf centos_ssl.tar && \ mv libcrypto.so.1.0.2k /usr/lib/libcrypto.so.1.0.2k && mv libssl.so.1.0.2k /usr/lib/libssl.so.1.0.2k && \ ln -sf /usr/lib/libcrypto.so.1.0.2k /usr/lib/libcrypto.so.10 && \ ln -sf /usr/lib/libssl.so.1.0.2k /usr/lib/libssl.so.10 && \ ln -sf /usr/lib/libcrypto.so.10 /usr/lib/libcrypto.so && \ ln -sf /usr/lib/libssl.so.10 /usr/lib/libssl.so
Ubuntu 16.04/18.04 环境配置(第一步)
一.环境准备
- Python 版本 3.6/3.7/3.8/3.9 (64 bit)
二.选择 CPU/GPU
如果您的计算机有 NVIDIA® GPU,请确保满足以下条件
三.安装必要工具
更新系统源
更新
apt的源:textapt update安装工具
bzip2以及make:textapt install -y bzip2textapt install -y makecmake 需要3.15以上,建议使用3.16.0:
textwget -q https://cmake.org/files/v3.16/cmake-3.16.0-Linux-x86_64.tar.gztexttar -zxvf cmake-3.16.0-Linux-x86_64.tar.gztextrm cmake-3.16.0-Linux-x86_64.tar.gztextPATH=/home/cmake-3.16.0-Linux-x86_64/bin:$PATHgcc 需要5.4以上,建议使用8.2.0:
textwget -q https://paddle-docker-tar.bj.bcebos.com/home/users/tianshuo/bce-python-sdk-0.8.27/gcc-8.2.0.tar.xz && \ tar -xvf gcc-8.2.0.tar.xz && \ cd gcc-8.2.0 && \ sed -i 's#ftp://gcc.gnu.org/pub/gcc/infrastructure/#https://paddle-ci.gz.bcebos.com/#g' ./contrib/download_prerequisites && \ unset LIBRARY_PATH CPATH C_INCLUDE_PATH PKG_CONFIG_PATH CPLUS_INCLUDE_PATH INCLUDE && \ ./contrib/download_prerequisites && \ cd .. && mkdir temp_gcc82 && cd temp_gcc82 && \ ../gcc-8.2.0/configure --prefix=/usr/local/gcc-8.2 --enable-threads=posix --disable-checking --disable-multilib && \ make -j8 && make install安装GOLANG
建议使用 go1.17.2:
textwget -qO- https://go.dev/dl/go1.17.2.linux-amd64.tar.gz | \ tar -xz -C /usr/local && \ mkdir /root/go && \ mkdir /root/go/bin && \ mkdir /root/go/src && \ echo "GOROOT=/usr/local/go" >> /root/.bashrc && \ echo "GOPATH=/root/go" >> /root/.bashrc && \ echo "PATH=/usr/local/go/bin:/root/go/bin:$PATH" >> /root/.bashrc source /root/.bashrc安装依赖库
安装相关依赖库 patchelf:
textapt-get install patchelf配置 ssl 依赖库
textwget https://paddle-serving.bj.bcebos.com/others/centos_ssl.tar && \ tar xf centos_ssl.tar && rm -rf centos_ssl.tar && \ mv libcrypto.so.1.0.2k /usr/lib/libcrypto.so.1.0.2k && mv libssl.so.1.0.2k /usr/lib/libssl.so.1.0.2k && \ ln -sf /usr/lib/libcrypto.so.1.0.2k /usr/lib/libcrypto.so.10 && \ ln -sf /usr/lib/libssl.so.1.0.2k /usr/lib/libssl.so.10 && \ ln -sf /usr/lib/libcrypto.so.10 /usr/lib/libcrypto.so && \ ln -sf /usr/lib/libssl.so.10 /usr/lib/libssl.so
Windows 环境配置(第一步)
由于受限第三方库的支持,Windows平台目前只支持用web service的方式搭建local predictor预测服务。
一.环境准备
- Python 版本 3.6/3.7/3.8/3.9 (64 bit)
二.选择 CPU/GPU
如果您的计算机有 NVIDIA® GPU,请确保满足以下条件
三.安装必要工具
更新 wget 工具
在链接下载wget,解压后复制到
C:\Windows\System32下,如有安全提示需要通过。安装git工具
详情参见Git官网
安装必要的C++库(可选)
部分用户可能会在
import paddle阶段遇见dll无法链接的问题,建议安装Visual Studio社区版本 ,并且安装C++的相关组件。
使用 pip 安装(第二步)
一. 安装服务 whl 包
服务 whl 包包括: client、app、server,其中 Server 分为 CPU 和 GPU,GPU 包根据您的环境选择一种安装
pip3 install paddle-serving-client==0.8.3 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip3 install paddle-serving-app==0.8.3 -i https://pypi.tuna.tsinghua.edu.cn/simple
# CPU Server
pip3 install paddle-serving-server==0.8.3 -i https://pypi.tuna.tsinghua.edu.cn/simple
# GPU Server,需要确认环境再选择执行哪一条,推荐使用CUDA 10.2的包
# CUDA10.2 + Cudnn7 + TensorRT6(推荐)
pip3 install paddle-serving-server-gpu==0.8.3.post102 -i https://pypi.tuna.tsinghua.edu.cn/simple
# CUDA10.1 + TensorRT6
pip3 install paddle-serving-server-gpu==0.8.3.post101 -i https://pypi.tuna.tsinghua.edu.cn/simple
# CUDA11.2 + TensorRT8
pip3 install paddle-serving-server-gpu==0.8.3.post112 -i https://pypi.tuna.tsinghua.edu.cn/simple 默认开启国内清华镜像源来加速下载,如果您使用 HTTP 代理可以关闭(-i https://pypi.tuna.tsinghua.edu.cn/simple)
二. 安装 Paddle 相关 Python 库
当您使用paddle_serving_client.convert命令或者Python Pipeline 框架时才需要安装。
# CPU 环境请执行
pip3 install paddlepaddle==2.2.2
# GPU CUDA 10.2环境请执行
pip3 install paddlepaddle-gpu==2.2.2注意: 如果您的 Cuda 版本不是10.2,或者您需要在 GPU 环境上使用 TensorRT,请勿直接执行上述命令,需要参考Paddle-Inference官方文档-下载安装Linux预测库选择相应的 GPU 环境的 url 链接并进行安装。
三. 安装完成后的环境检查
当以上步骤均完成后可使用命令行运行环境检查功能,自动运行 Paddle Serving 相关示例,进行环境相关配置校验。
python3 -m paddle_serving_server.serve check
# 以下输出表明环境检查正常
(Cmd) check_all
PaddlePaddle inference environment running success
C++ cpu environment running success
C++ gpu environment running success
Pipeline cpu environment running success
Pipeline gpu environment running success详情请参考环境检查文档
File: doc/Java_SDK_CN.md
Paddle Serving Client Java SDK
(简体中文|English)
Paddle Serving 提供了 Java SDK,支持 Client 端用 Java 语言进行预测,本文档说明了如何使用 Java SDK。
快速开始
环境要求
- Java 8 or higher
- Apache Maven下表显示了 Paddle Serving Server 和 Java SDK 之间的兼容性
| Paddle Serving Server version | Java SDK version |
|---|---|
| 0.9.0 | 0.0.1 |
- 直接使用提供的Java SDK作为Client进行预测
安装
您可以直接下载 jar,安装到本地 Maven 库:
wget https://paddle-serving.bj.bcebos.com/jar/paddle-serving-sdk-java-0.0.1.jar
mvn install:install-file -Dfile=$PWD/paddle-serving-sdk-java-0.0.1.jar -DgroupId=io.paddle.serving.client -DartifactId=paddle-serving-sdk-java -Dversion=0.0.1 -Dpackaging=jarMaven 配置
<dependency>
<groupId>io.paddle.serving.client</groupId>
<artifactId>paddle-serving-sdk-java</artifactId>
<version>0.0.1</version>
</dependency>File: doc/Java_SDK_EN.md
Paddle Serving Client Java SDK
(简体中文|English)
Paddle Serving provides Java SDK,which supports predict on the Client side with Java language. This document shows how to use the Java SDK.
Getting started
Prerequisites
- Java 8 or higher
- Apache MavenThe following table shows compatibilities between Paddle Serving Server and Java SDK.
| Paddle Serving Server version | Java SDK version |
|---|---|
| 0.9.0 | 0.0.1 |
- Directly use the provided Java SDK as the client for prediction
Install Java SDK
You can download jar and install it to the local Maven repository:
wget https://paddle-serving.bj.bcebos.com/jar/paddle-serving-sdk-java-0.0.1.jar
mvn install:install-file -Dfile=$PWD/paddle-serving-sdk-java-0.0.1.jar -DgroupId=io.paddle.serving.client -DartifactId=paddle-serving-sdk-java -Dversion=0.0.1 -Dpackaging=jarMaven configure
<dependency>
<groupId>io.paddle.serving.client</groupId>
<artifactId>paddle-serving-sdk-java</artifactId>
<version>0.0.1</version>
</dependency>Use it after compiling from the source code. See the document.
examples for using the java client, see the See the document.
File: doc/Latest_Packages_CN.md
Wheel包下载
(简体中文|English)
Paddle-Serving-Server (x86 CPU/GPU)
查找下面表格,拷贝链接地址,并运行 pip3 install。例如要安装 paddle-serving-server-0.0.0-py3-non-any.whl, 请右键点击链接拷贝链接地址,最终命令是pip3 install https://paddle-serving.bj.bcebos.com/test-dev/whl/paddle_serving_server-0.0.0-py3-none-any.whl。
二进制包(Binary Package)
大多数用户不会用到此章节。但是如果你在无网络的环境下部署Paddle Serving,在首次启动Serving时,无法下载二进制tar文件。因此,提供多种环境二进制包的下载链接,下载后传到无网络环境的指定目录下,即可使用。
如何离线设置SERVING_BIN?
- 下载Serving Server Wheel包和二进制tar包,确保它们与环境是一致的
- 下载Serving Client Wheel包和Serving App wheel包, 同时注意Python版本要一致.
pip install所有Wheel包 andtar xf二进制tar包, 然后export SERVING_BIN=$PWD/serving-gpu-cuda11-0.0.0/serving(以Cuda 11为例)
paddle-serving-client Wheel包
paddle-serving-app Wheel包
| develop whl | stable whl | |
|---|---|---|
| Python3 | paddle_serving_app-0.0.0-py3-none-any.whl | paddle_serving_app-0.9.0-py3-none-any.whl |
百度昆仑芯片
对于使用百度昆仑芯片的用户, 通过以下方式下载arm-xpu 或 x86-xpu Wheel包。选择 xpu-beta docker DOCKER镜像
昆仑环境仅支持python36
Wheel包链接
适用ARM CPU环境的昆仑Wheel包:
# paddle-serving-server
wget https://paddle-serving.bj.bcebos.com/test-dev/whl/arm/paddle_serving_app-0.9.0-py3-none-any.whl
# paddle-serving-client
wget https://paddle-serving.bj.bcebos.com/test-dev/whl/arm/paddle_serving_client-0.9.0-cp36-none-any.whl
# paddle-serving-app
wget https://paddle-serving.bj.bcebos.com/test-dev/whl/arm/paddle_serving_server_xpu-0.9.0.post2-py3-none-any.whl
# SERVING BIN
wget https://paddle-serving.bj.bcebos.com/test-dev/bin/serving-xpu-aarch64-0.9.0.tar.gz适用于ARM & XPU 的 v0.9.0 版本 Wheel包:
https://paddle-serving.bj.bcebos.com/test-dev/whl/paddle_serving_server_xpu-0.9.0.post2-py3-none-any.whlFile: doc/Latest_Packages_EN.md
Download Wheel Packages
(English|简体中文)
Paddle-Serving-Server (x86 CPU/GPU)
Check the following table, and copy the address of hyperlink then run pip3 install. For example, if you want to install paddle-serving-server-0.0.0-py3-non-any.whl, right click the hyper link and copy the link address, the final command is pip3 install https://paddle-serving.bj.bcebos.com/test-dev/whl/paddle_serving_server-0.0.0-py3-none-any.whl.
Binary Package
for most users, we do not need to read this section. But if you deploy your Paddle Serving on a machine without network, you will encounter a problem that the binary executable tar file cannot be downloaded. Therefore, here we give you all the download links for various environment.
How to setup SERVING_BIN offline?
- download the serving server whl package and bin package, and make sure they are for the same environment
- download the serving client whl and serving app whl, pay attention to the Python version.
pip installthe serving andtar xfthe binary package, thenexport SERVING_BIN=$PWD/serving-gpu-cuda11-0.0.0/serving(take Cuda 11 as the example)
paddle-serving-client
paddle-serving-app
| develop whl | stable whl | |
|---|---|---|
| Python3 | paddle_serving_app-0.0.0-py3-none-any.whl | paddle_serving_app-0.9.0-py3-none-any.whl |
Baidu Kunlun user
for kunlun user who uses arm-xpu or x86-xpu can download the wheel packages as follows. Users should use the xpu-beta docker DOCKER IMAGES
We only support Python 3.6 for Kunlun Users.
Wheel Package Links
for arm kunlun user,
# paddle-serving-server
wget https://paddle-serving.bj.bcebos.com/test-dev/whl/arm/paddle_serving_app-0.9.0-py3-none-any.whl
# paddle-serving-client
wget https://paddle-serving.bj.bcebos.com/test-dev/whl/arm/paddle_serving_client-0.9.0-cp36-none-any.whl
# paddle-serving-app
wget https://paddle-serving.bj.bcebos.com/test-dev/whl/arm/paddle_serving_server_xpu-0.9.0.post2-py3-none-any.whl
# SERVING BIN
wget https://paddle-serving.bj.bcebos.com/test-dev/bin/serving-xpu-aarch64-0.9.0.tar.gzfor x86 xpu user, the wheel packages are here.
https://paddle-serving.bj.bcebos.com/test-dev/whl/paddle_serving_server_xpu-0.9.0.post2-py3-none-any.whlFile: doc/LOD_CN.md
[Binary file]
File: doc/LOD_EN.md
Lod Introduction
(English|简体中文)
Principle
Explanation of Tensor and Padding, Please refer to paddlepaddle official website description.
LoD(Level-of-Detail) Tensor is an advanced feature of paddle and an extension of tensor. LoD Tensor improves training efficiency by sacrificing flexibility, reducing the impact of data expansion brought by padding.
Notice: For most users, there is no need to pay attention to the usage of LoD Tensor. Currently, serving only supports the usage of one-dimensional LOD.
Use
Prerequisite: Your prediction model needs to support variable length tensor input.
Take the visual task as an example. In the visual task, we often need to process video and image. These elements are high-dimensional objects.
Suppose that an existing Mini batch contains three videos, each video contains three frames, one frame and two frames respectively.
If each frame has the same size: 640x480, the mini batch can be expressed as:
3 1 2
口口口 口 口口The size of the bottom tenor is (3 + 1 + 2) x640x480, and each 口 represents a 640x480 image.
Then, the shape of tensor is [6,640,480], lod=[0,3,4,6].
Where 0 is the starting value and 3-0 = 3; 4-3=1; 6-4 = 2, these three values just represent your variable length information.
The last element 6 in LOD should be equal to the total length of the first dimension in shape.
The variable length information recorded in LOD and the first dimension information of shape in tensor should be aligned in the above way.
File: doc/Low_Precision_CN.md
Paddle Serving低精度部署
(简体中文|English)
低精度部署, 在Intel CPU上支持int8、bfloat16模型,Nvidia TensorRT支持int8、float16模型。
C++ Serving 部署量化模型
通过PaddleSlim量化生成低精度模型
详细见PaddleSlim量化
使用TensorRT int8加载PaddleSlim Int8量化模型进行部署
首先下载Resnet50 PaddleSlim量化模型,并转换为Paddle Serving支持的部署模型格式。
wget https://paddle-inference-dist.bj.bcebos.com/inference_demo/python/resnet50/ResNet50_quant.tar.gz
tar zxvf ResNet50_quant.tar.gz
python -m paddle_serving_client.convert --dirname ResNet50_quant启动rpc服务, 设定所选GPU id、部署模型精度
python -m paddle_serving_server.serve --model serving_server --port 9393 --gpu_ids 0 --use_trt --precision int8使用client进行请求
from paddle_serving_client import Client
from paddle_serving_app.reader import Sequential, File2Image, Resize, CenterCrop
from paddle_serving_app.reader import RGB2BGR, Transpose, Div, Normalize
client = Client()
client.load_client_config(
"resnet_v2_50_imagenet_client/serving_client_conf.prototxt")
client.connect(["127.0.0.1:9393"])
seq = Sequential([
File2Image(), Resize(256), CenterCrop(224), RGB2BGR(), Transpose((2, 0, 1)),
Div(255), Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225], True)
])
image_file = "daisy.jpg"
img = seq(image_file)
fetch_map = client.predict(feed={"image": img}, fetch=["score"])
print(fetch_map["score"].reshape(-1))Python Pipeline 部署量化模型
参考文档
- PaddleSlim
- PaddleInference Intel CPU部署量化模型文档
- PaddleInference NV GPU部署量化模型文档
File: doc/Low_Precision_EN.md
Low-Precision Deployment for Paddle Serving
(English|简体中文)
Intel CPU supports int8 and bfloat16 models, NVIDIA TensorRT supports int8 and float16 models.
Obtain the quantized model through PaddleSlim tool
Train the low-precision models please refer to PaddleSlim.
Deploy the quantized model from PaddleSlim using Paddle Serving with Nvidia TensorRT int8 mode
Firstly, download the Resnet50 int8 model and convert to Paddle Serving's saved model。
wget https://paddle-inference-dist.bj.bcebos.com/inference_demo/python/resnet50/ResNet50_quant.tar.gz
tar zxvf ResNet50_quant.tar.gz
python -m paddle_serving_client.convert --dirname ResNet50_quantStart RPC service, specify the GPU id and precision mode
python -m paddle_serving_server.serve --model serving_server --port 9393 --gpu_ids 0 --use_trt --precision int8Request the serving service with Client
from paddle_serving_client import Client
from paddle_serving_app.reader import Sequential, File2Image, Resize, CenterCrop
from paddle_serving_app.reader import RGB2BGR, Transpose, Div, Normalize
client = Client()
client.load_client_config(
"serving_client/serving_client_conf.prototxt")
client.connect(["127.0.0.1:9393"])
seq = Sequential([
File2Image(), Resize(256), CenterCrop(224), RGB2BGR(), Transpose((2, 0, 1)),
Div(255), Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225], True)
])
image_file = "daisy.jpg"
img = seq(image_file)
fetch_map = client.predict(feed={"image": img}, fetch=["save_infer_model/scale_0.tmp_0"])
print(fetch_map["save_infer_model/scale_0.tmp_0"].reshape(-1))Reference
- PaddleSlim
- Deploy the quantized model Using Paddle Inference on Intel CPU
- Deploy the quantized model Using Paddle Inference on Nvidia GPU
File: doc/Model_Zoo_CN.md
模型库
Paddle Serving 已实现9个类别,共计46个模型的服务化部署示例。
模型分类
一.图像分类与识别
模型部署示例请参阅下表:
| 场景 | 模型 | 类型 | 示例使用的框架 | 下载 |
|---|---|---|---|---|
| 图像识别 | pp_shitu | PaddleClas | C++ Serving | .tar.gz |
| 图像分类 | resnet_v2_50_imagenet | PaddleClas | C++ ServingPipeline Serving | .tar.gz |
| 图像分类 | mobilenet_v2_imagenet | PaddleClas | C++ Serving | .tar.gz |
| 图像分类 | resnet50_vd | PaddleClas | C++ ServingPipeline Serving | .tar.gz |
| 图像分类 | ResNet50_vd_KL | PaddleClas | Pipeline Serving | .tar |
| 图像分类 | ResNet50_vd_FPGM | PaddleClas | Pipeline Serving | .tar |
| 图像分类 | ResNet50_vd_PACT | PaddleClas | Pipeline Serving | .tar |
| 图像分类 | ResNeXt101_vd_64x4d | PaddleClas | Pipeline Serving | .tar |
| 图像分类 | DarkNet53 | PaddleClas | Pipeline Serving | .tar |
| 图像分类 | MobileNetV1 | PaddleClas | Pipeline Serving | .tar |
| 图像分类 | MobileNetV2 | PaddleClas | Pipeline Serving | .tar |
| 图像分类 | MobileNetV3_large_x1_0 | PaddleClas | Pipeline Serving | .tar |
| 图像生成 | HRNet_W18_C | PaddleClas | Pipeline Serving | .tar |
| 图像分类 | ShuffleNetV2_x1_0 | PaddleClas | Pipeline Serving | .tar |
二.文本类
模型部署示例请参阅下表:
| 场景 | 模型 | 类型 | 示例使用的框架 | 下载 |
|---|---|---|---|---|
| 文本生成 | bert_chinese_L-12_H-768_A-12 | PaddleNLP | C++ ServingPipeline Serving | .tar.gz |
| 情感分析 | senta_bilstm | PaddleNLP | C++ Serving | .tar.gz |
| 词法分析 | lac | PaddleNLP | C++ Serving | .tar.gz |
| 机器翻译 | transformer | PaddleNLP | Pipeline Serving | model |
| 标点符号预测 | ELECTRA | PaddleNLP | Pipeline Serving | model |
| 抽取文本向量 | In-batch Negatives | PaddleNLP | Pipeline Serving | model |
三.推荐系统
模型部署示例请参阅下表:
| 场景 | 模型 | 类型 | 示例使用的框架 | 下载 |
|---|---|---|---|---|
| CTR预估 | criteo_ctr | PaddleRec | C++ Serving | .tar.gz |
| CTR预估 | criteo_ctr_with_cube | PaddleRec | C++ Serving | .tar.gz |
| 内容推荐 | wide&deep | PaddleRec | C++ Serving | model |
四.人脸识别
模型部署示例请参阅下表:
| 场景 | 模型 | 类型 | 示例使用的框架 | 下载 |
|---|---|---|---|---|
| 人脸识别 | blazeface | PaddleDetection | C++ Serving | .tar.gz |
五.目标检测
模型部署示例请参阅下表:
| 场景 | 模型 | 类型 | 示例使用的框架 | 下载 |
|---|---|---|---|---|
| 目标检测 | cascade_mask_rcnn_r50_vd_fpn_ssld_2x_coco | PaddleDetection | C++ Serving | .tar.gz |
| 目标检测 | yolov4 | PaddleDetection | C++ Serving | .tar.gz |
| 目标检测 | fcos_dcn_r50_fpn_1x_coco | PaddleDetection | C++ Serving | .tar.gz |
| 目标检测 | ssd_vgg16_300_240e_voc | PaddleDetection | C++ Serving | .tar |
| 目标检测 | yolov3_darknet53_270e_coco | PaddleDetection | C++ ServingPipeline Serving | .tar |
| 目标检测 | faster_rcnn_r50_fpn_1x_coco | PaddleDetection | C++ ServingPipeline Serving | .tar |
| 目标检测 | ppyolo_r50vd_dcn_1x_coco | PaddleDetection | C++ Serving | .tar |
| 目标检测 | ppyolo_mbv3_large_coco | PaddleDetection | Pipeline Serving | .tar |
| 目标检测 | ttfnet_darknet53_1x_coco | PaddleDetection | C++ Serving | .tar |
| 目标检测 | YOLOv3-DarkNet | PaddleDetection | C++ Serving | .pdparams.yml |
六.文字识别
模型部署示例请参阅下表:
| 场景 | 模型 | 类型 | 示例使用的框架 | 下载 |
|---|---|---|---|---|
| 文字识别 | ocr_rec | PaddleOCR | C++ ServingPipeline Serving | .tar.gz |
| 文字识别 | ocr_det | PaddleOCR | C++ ServingPipeline Serving | .tar.gz |
| 文字识别 | ch_ppocr_mobile_v2.0_det | PaddleOCR | Pipeline Serving | model.yml |
| 文字识别 | ch_ppocr_server_v2.0_det | PaddleOCR | Pipeline Serving | model.yml |
| 文字识别 | ch_ppocr_mobile_v2.0_rec | PaddleOCR | Pipeline Serving | model.yml |
| 文字识别 | ch_ppocr_server_v2.0_rec | PaddleOCR | Pipeline Serving | model.yml |
| 文字识别 | ch_ppocr_mobile_v2.0 | PaddleOCR | Pipeline Serving | model |
| 文字识别 | ch_ppocr_server_v2.0 | PaddleOCR | Pipeline Serving | model |
七.图像分割
模型部署示例请参阅下表:
| 场景 | 模型 | 类型 | 示例使用的框架 | 下载 |
|---|---|---|---|---|
| 图像分割 | deeplabv3 | PaddleSeg | C++ Serving | .tar.gz |
| 图像分割 | unet | PaddleSeg | C++ Serving | .tar.gz |
八.关键点检测
模型部署示例请参阅下表:
| 场景 | 模型 | 类型 | 示例使用的框架 | 下载 |
|---|---|---|---|---|
| 关键点检测 | faster_rcnn_hrnetv2p_w18_1x | PaddleDetection | C++ Serving | .tar.gz |
九.视频理解
模型部署示例请参阅下表:
| 场景 | 模型 | 类型 | 示例使用的框架 | 下载 |
|---|---|---|---|---|
| 视频理解 | PPTSN_K400 | PaddleVideo | Pipeline Serving | model |
模型示例库
Paddle Serving 代码库下模型部署示例请参考 examples 目录。更多 Paddle Serving 部署模型请参考 wholechain。
了解最新模型,请进入 Paddle 模型套件库:
File: doc/Model_Zoo_EN.md
Model Zoo
(English|简体中文)
This page lists model archives that are pre-trained and pre-packaged, ready to be served for inference with PaddleServing.
To propose a model for inclusion, please submit pull request
Special thanks to the Padddle wholechain and PaddleHub whose Model Zoo and Model Examples were used in generating these model archives
| Model | Type | Framework | Download |
|---|---|---|---|
| pp_shitu | PaddleClas | C++ Serving | .tar.gz |
| resnet_v2_50_imagenet | PaddleClas | C++ ServingPipeline Serving | .tar.gz |
| mobilenet_v2_imagenet | PaddleClas | C++ Serving | .tar.gz |
| resnet50_vd | PaddleClas | C++ ServingPipeline Serving | .tar.gz |
| ResNet50_vd_KL | PaddleClas | Pipeline Serving | .tar |
| ResNet50_vd_FPGM | PaddleClas | Pipeline Serving | .tar |
| ResNet50_vd_PACT | PaddleClas | Pipeline Serving | .tar |
| ResNeXt101_vd_64x4d | PaddleClas | Pipeline Serving | .tar |
| DarkNet53 | PaddleClas | Pipeline Serving | .tar |
| MobileNetV1 | PaddleClas | Pipeline Serving | .tar |
| MobileNetV2 | PaddleClas | Pipeline Serving | .tar |
| MobileNetV3_large_x1_0 | PaddleClas | Pipeline Serving | .tar |
| HRNet_W18_C | PaddleClas | Pipeline Serving | .tar |
| ShuffleNetV2_x1_0 | PaddleClas | Pipeline Serving | .tar |
| bert_chinese_L-12_H-768_A-12 | PaddleNLP | C++ ServingPipeline Serving | .tar.gz |
| senta_bilstm | PaddleNLP | C++ Serving | .tar.gz |
| lac | PaddleNLP | C++ Serving | .tar.gz |
| transformer | PaddleNLP | Pipeline Serving | model |
| criteo_ctr | PaddleRec | C++ Serving | .tar.gz |
| criteo_ctr_with_cube | PaddleRec | C++ Serving | .tar.gz |
| wide&deep | PaddleRec | C++ Serving | model |
| blazeface | PaddleDetection | C++ Serving | .tar.gz |
| cascade_mask_rcnn_r50_vd_fpn_ssld_2x_coco | PaddleDetection | C++ Serving | .tar.gz |
| yolov4 | PaddleDetection | C++ Serving | .tar.gz |
| faster_rcnn_hrnetv2p_w18_1x | PaddleDetection | C++ Serving | .tar.gz |
| fcos_dcn_r50_fpn_1x_coco | PaddleDetection | C++ Serving | .tar.gz |
| ssd_vgg16_300_240e_voc | PaddleDetection | C++ Serving | .tar |
| yolov3_darknet53_270e_coco | PaddleDetection | C++ ServingPipeline Serving | .tar |
| faster_rcnn_r50_fpn_1x_coco | PaddleDetection | C++ ServingPipeline Serving | .tar |
| ppyolo_r50vd_dcn_1x_coco | PaddleDetection | C++ Serving | .tar |
| ppyolo_mbv3_large_coco | PaddleDetection | Pipeline Serving | .tar |
| ttfnet_darknet53_1x_coco | PaddleDetection | C++ Serving | .tar |
| YOLOv3-DarkNet | PaddleDetection | C++ Serving | .pdparams.yml |
| ocr_rec | PaddleOCR | C++ ServingPipeline Serving | .tar.gz |
| ocr_det | PaddleOCR | C++ ServingPipeline Serving | .tar.gz |
| ch_ppocr_mobile_v2.0_det | PaddleOCR | Pipeline Serving | model.yml |
| ch_ppocr_server_v2.0_det | PaddleOCR | Pipeline Serving | model.yml |
| ch_ppocr_mobile_v2.0_rec | PaddleOCR | Pipeline Serving | model.yml |
| ch_ppocr_server_v2.0_rec | PaddleOCR | Pipeline Serving | model.yml |
| ch_ppocr_mobile_v2.0 | PaddleOCR | Pipeline Serving | model |
| ch_ppocr_server_v2.0 | PaddleOCR | Pipeline Serving | model |
| deeplabv3 | PaddleSeg | C++ Serving | .tar.gz |
| unet | PaddleSeg | C++ Serving | .tar.gz |
| PPTSN_K400 | PaddleVideo | Pipeline Serving | model |
Refer example for more details on above models.
Refer wholechain for more pre-trained models supported by PaddleServing
Latest models refer
File: doc/Process_data_CN.md
[Binary file]
File: doc/Prometheus_CN.md
Paddle Serving使用普罗米修斯监控
Paddle Serving支持普罗米修斯进行性能数据的监控。默认的访问接口为http://localhost:19393/metrics。数据形式为文本格式,您可以使用如下命令直观的看到:
curl http://localhost:19393/metrics配置使用
C++ Server
对于 C++ Server 来说,启动服务时请添加如下参数
| 参数 | 参数说明 | 备注 |
|---|---|---|
| enable_prometheus | 开启Prometheus | 开启Prometheus功能 |
| prometheus_port | Prometheus数据端口 | 默认为19393 |
Python Pipeline
对于 Python Pipeline 来说,启动服务时请在配置文件config.yml中添加如下参数
dag:
#开启Prometheus
enable_prometheus: True
#配置Prometheus数据端口
prometheus_port: 19393监控数据类型
监控数据类型如下表
| Metric | Frequency | Description |
|---|---|---|
pd_query_request_success_total |
Per request | Number of successful query requests |
pd_query_request_failure_total |
Per request | Number of failed query requests |
pd_inference_count_total |
Per request | Number of inferences performed |
pd_query_request_duration_us_total |
Per request | Cumulative end-to-end query request handling time |
pd_inference_duration_us_total |
Per request | Cumulative time requests spend executing the inference model |
监控示例
此处给出一个使用普罗米修斯进行服务监控的简单示例
1、获取镜像
docker pull prom/node-exporter
docker pull prom/prometheus2、运行镜像
docker run -d -p 9100:9100 \
-v "/proc:/host/proc:ro" \
-v "/sys:/host/sys:ro" \
-v "/:/rootfs:ro" \
--net="host" \
prom/node-exporter3、配置
修改监控服务的配置文件/opt/prometheus/prometheus.yml,添加监控节点信息
global:
scrape_interval: 60s
evaluation_interval: 60s
scrape_configs:
- job_name: prometheus
static_configs:
- targets: ['localhost:9090']
labels:
instance: prometheus
- job_name: linux
static_configs:
- targets: ['$IP:9100']
labels:
instance: localhost4、启动监控服务
docker run -d \
-p 9090:9090 \
-v /opt/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml \
prom/prometheus访问 http://serverip:9090/graph 即可
File: doc/Quick_Start_CN.md
[Binary file]
File: doc/Quick_Start_EN.md
Paddle Serving Quick Start Examples
(English|简体中文)
This quick start example is mainly for those users who already have a model to deploy, and we also provide a model that can be used for deployment. in case if you want to know how to complete the process from offline training to online service, please refer to the AiStudio tutorial above.
Boston House Price Prediction model
get into the Serving git directory, and change dir to fit_a_line
cd Serving/examples/C++/fit_a_line
sh get_data.shPaddle Serving provides HTTP and RPC based service for users to access
RPC service
A user can also start a RPC service with paddle_serving_server.serve. RPC service is usually faster than HTTP service, although a user needs to do some coding based on Paddle Serving's python client API. Note that we do not specify --name here.
python3 -m paddle_serving_server.serve --model uci_housing_model --thread 10 --port 9292For a complete list of parameters, see the document Serving Configuration
# A user can visit rpc service through paddle_serving_client API
from paddle_serving_client import Client
import numpy as np
client = Client()
client.load_client_config("uci_housing_client/serving_client_conf.prototxt")
client.connect(["127.0.0.1:9292"])
data = [0.0137, -0.1136, 0.2553, -0.0692, 0.0582, -0.0727,
-0.1583, -0.0584, 0.6283, 0.4919, 0.1856, 0.0795, -0.0332]
fetch_map = client.predict(feed={"x": np.array(data).reshape(1,13,1)}, fetch=["price"])
print(fetch_map)Here, client.predict function has two arguments. feed is a python dict with model input variable alias name and values. fetch assigns the prediction variables to be returned from servers. In the example, the name of "x" and "price" are assigned when the servable model is saved during training.
WEB service
Users can also put the data format processing logic on the server side, so that they can directly use curl to access the service, refer to the following case whose path is Serving/examples/C++/fit_a_line
python3 -m paddle_serving_server.serve --model uci_housing_model --thread 10 --port 9292for client side,
curl -H "Content-Type:application/json" -X POST -d '{"feed":[{"x": [0.0137, -0.1136, 0.2553, -0.0692, 0.0582, -0.0727, -0.1583, -0.0584, 0.6283, 0.4919, 0.1856, 0.0795, -0.0332]}], "fetch":["price"]}' http://127.0.0.1:9292/uci/predictionthe response is
{"result":{"price":[[18.901151657104492]]}}Pipeline Service
Paddle Serving provides industry-leading multi-model tandem services, which strongly supports the actual operating business scenarios of major companies, please refer to OCR word recognition.
we get two models
python3 -m paddle_serving_app.package --get_model ocr_rec
tar -xzvf ocr_rec.tar.gz
python3 -m paddle_serving_app.package --get_model ocr_det
tar -xzvf ocr_det.tar.gzthen we start server side, launch two models as one standalone web service
python3 web_service.pyhttp request
python3 pipeline_http_client.pygrpc request
python3 pipeline_rpc_client.pyoutput
{'err_no': 0, 'err_msg': '', 'key': ['res'], 'value': ["['土地整治与土壤修复研究中心', '华南农业大学1素图']"]}Stop Serving/Pipeline service
Method one :Ctrl+C to quit
Method Two :In the path where starting the Serving/Pipeline service or the path which environment variable SERVING_HOME set (the file named ProcessInfo.json exists in this path)
python3 -m paddle_serving_server.serve stopFile: doc/Run_On_DCU_CN.md
Paddle Serving使用海光芯片部署
Paddle Serving支持使用海光DCU进行预测部署。目前支持的ROCm版本为4.0.1。
安装Docker镜像
我们推荐使用docker部署Serving服务,可以直接从Paddle的官方镜像库拉取预先装有ROCm4.0.1的docker镜像。
# 拉取镜像
docker pull paddlepaddle/paddle:latest-dev-rocm4.0-miopen2.11
# 启动容器,注意这里的参数,例如shm-size, device等都需要配置
docker run -it --name paddle-rocm-dev --shm-size=128G \
--device=/dev/kfd --device=/dev/dri --group-add video \
--cap-add=SYS_PTRACE --security-opt seccomp=unconfined \
paddlepaddle/paddle:latest-dev-rocm4.0-miopen2.11 /bin/bash
# 检查容器是否可以正确识别海光DCU设备
rocm-smi
# 预期得到以下结果:
======================= ROCm System Management Interface =======================
================================= Concise Info =================================
GPU Temp AvgPwr SCLK MCLK Fan Perf PwrCap VRAM% GPU%
0 50.0c 23.0W 1319Mhz 800Mhz 0.0% auto 300.0W 0% 0%
1 48.0c 25.0W 1319Mhz 800Mhz 0.0% auto 300.0W 0% 0%
2 48.0c 24.0W 1319Mhz 800Mhz 0.0% auto 300.0W 0% 0%
3 49.0c 27.0W 1319Mhz 800Mhz 0.0% auto 300.0W 0% 0%
================================================================================
============================= End of ROCm SMI Log ==============================编译、安装
基本环境配置可参考该文档进行配置。
编译
- 编译server部分
cd Serving
mkdir -p server-build-dcu && cd server-build-dcu
cmake -DPYTHON_INCLUDE_DIR=/opt/conda/include/python3.7m/ \
-DPYTHON_LIBRARIES=/opt/conda/lib/libpython3.7m.so \
-DPYTHON_EXECUTABLE=/opt/conda/bin/python \
-DWITH_MKL=ON \
-DWITH_ROCM=ON \
-DSERVER=ON ..
make -j10安装wheel包
编译步骤完成后,会在各自编译目录$build_dir/python/dist生成whl包,分别安装即可。例如server步骤,会在server-build-arm/python/dist目录下生成whl包, 使用命令pip install -u xxx.whl进行安装。
部署使用示例
以resnet50为例
启动rpc服务
启动rpc服务,基于1卡部署
python3 -m paddle_serving_server.serve --model resnet_v2_50_imagenet_model --port 9393 --gpu_ids 1其他说明
模型实例及说明
支持海光芯片部署模型列表见链接。不同模型适配上存在差异,可能存在不支持的情况,部署使用存在问题时,欢迎以Github issue,我们会实时跟进。
昆仑芯片支持相关参考资料
File: doc/Run_On_JETSON_CN.md
Paddle Serving使用JETSON部署
Paddle Serving支持使用JETSON进行预测部署。目前仅支持Pipeline模式。
安装PaddlePaddle
可以参考NV Jetson部署示例 安装python版本的paddlepaddle
安装PaddleServing
安装ARM版本的whl包
# paddle-serving-server
https://paddle-serving.bj.bcebos.com/whl/xpu/arm/paddle_serving_server_xpu-0.0.0.post2-py3-none-any.whl
# paddle-serving-client
https://paddle-serving.bj.bcebos.com/whl/xpu/arm/paddle_serving_client-0.0.0-cp36-none-any.whl
# paddle-serving-app
https://paddle-serving.bj.bcebos.com/whl/xpu/arm/paddle_serving_app-0.0.0-py3-none-any.whl部署使用
以Uci为例
启动服务
python3 web_service.py &>log.txt &其中修改config.yml中的对应配置项
#计算硬件类型: 空缺时由devices决定(CPU/GPU),0=cpu, 1=gpu, 2=tensorRT, 3=arm cpu, 4=kunlun xpu
device_type: 1
#计算硬件ID,优先由device_type决定硬件类型。devices为""或空缺时为CPU预测;当为"0", "0,1,2"时为GPU预测,表示使用的GPU卡
devices: "0,1"其他说明
Jetson支持相关参考资料
File: doc/Run_On_Kubernetes_CN.md
[Binary file]
File: doc/Run_On_NPU_CN.md
Paddle Serving使用昇腾NPU芯片部署
Paddle Serving支持使用昇腾NPU芯片进行预测部署。目前支持在昇腾芯片(910/310)和arm服务器上进行部署,后续完善对其他异构硬件服务器部署能力。
昇腾910
安装Docker镜像
我们推荐使用docker部署Serving服务,可以直接从Paddle的官方镜像库拉取预先装有 CANN 社区版 5.0.2.alpha005 的 docker 镜像。
# 拉取镜像
docker pull paddlepaddle/paddle:latest-dev-cann5.0.2.alpha005-gcc82-aarch64
# 启动容器,注意这里的参数 --device,容器仅映射设备ID为4到7的4张NPU卡,如需映射其他卡相应增改设备ID号即可
docker run -it --name paddle-npu-dev -v /home/<user_name>:/workspace \
--pids-limit 409600 --network=host --shm-size=128G \
--cap-add=SYS_PTRACE --security-opt seccomp=unconfined \
--device=/dev/davinci4 --device=/dev/davinci5 \
--device=/dev/davinci6 --device=/dev/davinci7 \
--device=/dev/davinci_manager \
--device=/dev/devmm_svm \
--device=/dev/hisi_hdc \
-v /usr/local/Ascend/driver:/usr/local/Ascend/driver \
-v /usr/local/bin/npu-smi:/usr/local/bin/npu-smi \
-v /usr/local/dcmi:/usr/local/dcmi \
paddlepaddle/paddle:latest-dev-cann5.0.2.alpha005-gcc82-aarch64 /bin/bash
# 检查容器中是否可以正确识别映射的昇腾DCU设备
npu-smi info
# 预期得到类似如下的结果
+------------------------------------------------------------------------------------+
| npu-smi 1.9.3 Version: 21.0.rc1 |
+----------------------+---------------+---------------------------------------------+
| NPU Name | Health | Power(W) Temp(C) |
| Chip | Bus-Id | AICore(%) Memory-Usage(MB) HBM-Usage(MB) |
+======================+===============+=============================================+
| 4 910A | OK | 67.2 30 |
| 0 | 0000:C2:00.0 | 0 303 / 15171 0 / 32768 |
+======================+===============+=============================================+
| 5 910A | OK | 63.8 25 |
| 0 | 0000:82:00.0 | 0 2123 / 15171 0 / 32768 |
+======================+===============+=============================================+
| 6 910A | OK | 67.1 27 |
| 0 | 0000:42:00.0 | 0 1061 / 15171 0 / 32768 |
+======================+===============+=============================================+
| 7 910A | OK | 65.5 30 |
| 0 | 0000:02:00.0 | 0 2563 / 15078 0 / 32768 |
+======================+===============+=============================================+编译、安装
基本环境配置可参考该文档进行配置。
1、依赖安装
安装编译所需依赖库,包括patchelf、libcurl等
apt-get install patchelf libcurl4-openssl-dev libbz2-dev libgeos-dev2、GOLANG环境配置
下载并配置ARM版本的GOLANG-1.17.2
wget https://golang.org/dl/go1.17.2.linux-arm64.tar.gz
tar zxvf go1.17.2.linux-arm64.tar.gz -C /usr/local/
mkdir /root/go /root/go/bin /root/go/src
echo "GOROOT=/usr/local/go" >> /root/.bashrc
echo "GOPATH=/root/go" >> /root/.bashrc
echo "PATH=/usr/local/go/bin:/root/go/bin:$PATH" >> /root/.bashrc
source /root/.bashrc
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct
go install github.com/grpc-ecosystem/grpc-gateway/[email protected]
go install github.com/grpc-ecosystem/grpc-gateway/[email protected]
go install github.com/golang/protobuf/[email protected]
go install google.golang.org/[email protected]
go env -w GO111MODULE=auto3、PYTHON环境配置
下载python依赖库并配置环境
pip3.7 install -r python/requirements.txt -i https://mirror.baidu.com/pypi/simple
export PYTHONROOT=/opt/conda
export PYTHON_INCLUDE_DIR=$PYTHONROOT/include/python3.7m
export PYTHON_LIBRARIES=$PYTHONROOT/lib/libpython3.7m.so
export PYTHON_EXECUTABLE=$PYTHONROOT/bin/python3.74、编译server
mkdir build-server-npu && cd build-server-npu
cmake -DPYTHON_INCLUDE_DIR=$PYTHON_INCLUDE_DIR/ \
-DPYTHON_LIBRARIES=$PYTHON_LIBRARIES \
-DPYTHON_EXECUTABLE=$PYTHON_EXECUTABLE \
-DCMAKE_INSTALL_PREFIX=./output \
-DWITH_ASCEND_CL=ON \
-DSERVER=ON ..
make TARGET=ARMV8 -j165、安装编译包
编译步骤完成后,会在各自编译目录$build_dir/python/dist生成whl包,分别安装即可。例如server步骤,会在server-build-npu/python/dist目录下生成whl包, 使用命令pip install -u xxx.whl进行安装。
部署使用
为了支持arm+昇腾910服务部署,启动服务时需使用以下参数。
| 参数 | 参数说明 | 备注 |
|---|---|---|
| use_ascend_cl | 使用Ascend CL进行预测 | 使用Ascend预测能力 |
以Bert为例
启动rpc服务,使用Ascend npu优化加速能力
python3 -m paddle_serving_server.serve --model bert_seq128_model --thread 6 --port 9292 --use_ascend_cl昇腾310
安装Docker镜像
我们推荐使用docker部署Serving服务,可以拉取装有 CANN 3.3.0 docker 镜像。
# 拉取镜像
docker pull registry.baidubce.com/paddlepaddle/serving:ascend-aarch64-cann3.3.0-paddlelite-devel
# 启动容器,注意这里的参数 --device,容器仅映射设备ID为4到7的4张NPU卡,如需映射其他卡相应增改设备ID号即可
docker run -it --name paddle-npu-dev -v /home/<user_name>:/workspace \
--pids-limit 409600 --network=host --shm-size=128G \
--cap-add=SYS_PTRACE --security-opt seccomp=unconfined \
--device=/dev/davinci4 --device=/dev/davinci5 \
--device=/dev/davinci6 --device=/dev/davinci7 \
--device=/dev/davinci_manager \
--device=/dev/devmm_svm \
--device=/dev/hisi_hdc \
-v /usr/local/Ascend/driver:/usr/local/Ascend/driver \
-v /usr/local/bin/npu-smi:/usr/local/bin/npu-smi \
-v /usr/local/dcmi:/usr/local/dcmi \
registry.baidubce.com/paddlepaddle/serving:ascend-aarch64-cann3.3.0-paddlelite-devel /bin/bash编译、安装
基本环境配置可参考该文档进行配置。
1、PYTHON环境配置
下载python依赖库并配置环境
pip3.7 install -r python/requirements.txt -i https://mirror.baidu.com/pypi/simple
export PYTHONROOT=/usr/local/python3.7.5
export PYTHON_INCLUDE_DIR=$PYTHONROOT/include/python3.7m
export PYTHON_LIBRARIES=$PYTHONROOT/lib/libpython3.7m.so
export PYTHON_EXECUTABLE=$PYTHONROOT/bin/python3.72、编译server
mkdir build-server-npu && cd build-server-npu
cmake -DPYTHON_INCLUDE_DIR=$PYTHON_INCLUDE_DIR/ \
-DPYTHON_LIBRARIES=$PYTHON_LIBRARIES \
-DPYTHON_EXECUTABLE=$PYTHON_EXECUTABLE \
-DCMAKE_INSTALL_PREFIX=./output \
-DWITH_ASCEND_CL=ON \
-DWITH_LITE=ON \
-DSERVER=ON ..
make TARGET=ARMV8 -j163、安装编译包
编译步骤完成后,会在各自编译目录$build_dir/python/dist生成whl包,分别安装即可。例如server步骤,会在server-build-npu/python/dist目录下生成whl包, 使用命令pip install -u xxx.whl进行安装。
部署使用
为了支持arm+昇腾310服务部署,启动服务时需使用以下参数。
| 参数 | 参数说明 | 备注 |
|---|---|---|
| use_ascend_cl | 使用Ascend CL进行预测 | 使用Ascend预测能力 |
| use_lite | 使用Paddle-Lite Engine | 使用Paddle-Lite cpu预测能力 |
以resnet50为例
启动rpc服务,使用Paddle-Lite npu优化加速能力
python3 -m paddle_serving_server.serve --model resnet_v2_50_imagenet_model --thread 6 --port 9292 --use_ascend_cl --use_lite其他说明
NPU芯片支持相关参考资料
File: doc/Run_On_XPU_CN.md
Paddle Serving使用百度昆仑芯片部署
(简体中文|English)
Paddle Serving支持使用百度昆仑芯片进行预测部署。目前支持在百度昆仑芯片和arm服务器(如飞腾 FT-2000+/64), 或者百度昆仑芯片和Intel CPU服务器,上进行部署,后续完善对其他异构硬件服务器部署能力。
安装Docker镜像
我们推荐使用docker部署Serving服务,在xpu环境下可参考Docker镜像文档安装xpu镜像,并进一步完成编译、安装和部署等任务。
编译、安装
基本环境配置可参考该文档进行配置。下面以飞腾FT-2000+/64机器为例进行介绍。
编译
- 编译server部分
cd Serving
mkdir -p server-build-arm && cd server-build-arm
cmake -DPYTHON_INCLUDE_DIR=/usr/local/include/python3.7m/ \
-DPYTHON_LIBRARIES=/usr/local/lib/ \
-DPYTHON_EXECUTABLE=/usr/local/bin/python3.7 \
-DWITH_PYTHON=ON \
-DWITH_LITE=ON \
-DWITH_XPU=ON \
-DWITH_MKL=ON \
-DSERVER=ON ..
make -j10可以执行make install把目标产出放在./output目录下,cmake阶段需添加-DCMAKE_INSTALL_PREFIX=./output选项来指定存放路径。在支持AVX2指令集的Intel CPU平台上请指定-DWITH_MKL=ON编译选项。
- 编译client部分
mkdir -p client-build-arm && cd client-build-arm
cmake -DPYTHON_INCLUDE_DIR=/usr/local/include/python3.7m/ \
-DPYTHON_LIBRARIES=/usr/local/lib/ \
-DPYTHON_EXECUTABLE=/usr/local/bin/python3.7 \
-DWITH_PYTHON=ON \
-DWITH_LITE=ON \
-DWITH_XPU=ON \
-DCLIENT=ON ..
make -j10- 编译app部分
cd Serving
mkdir -p app-build-arm && cd app-build-arm
cmake -DPYTHON_INCLUDE_DIR=/usr/local/include/python3.7m/ \
-DPYTHON_LIBRARIES=/usr/local/lib/ \
-DPYTHON_EXECUTABLE=/usr/local/bin/python3.7 \
-DWITH_PYTHON=ON \
-DWITH_LITE=ON \
-DWITH_XPU=ON \
-DAPP=ON ..
make -j10安装wheel包
以上编译步骤完成后,会在各自编译目录$build_dir/python/dist生成whl包,分别安装即可。例如server步骤,会在server-build-arm/python/dist目录下生成whl包, 使用命令pip install -u xxx.whl进行安装。
请求参数说明
为了支持arm+xpu服务部署,使用Paddle-Lite加速能力,请求时需使用以下参数。
| 参数 | 参数说明 | 备注 |
|---|---|---|
| use_lite | 使用Paddle-Lite Engine | 使用Paddle-Lite cpu预测能力 |
| use_xpu | 使用Baidu Kunlun进行预测 | 该选项需要与use_lite配合使用 |
| ir_optim | 开启Paddle-Lite计算子图优化 | 详细见Paddle-Lite |
部署使用示例
下载模型
wget --no-check-certificate https://paddle-serving.bj.bcebos.com/uci_housing.tar.gz
tar -xzf uci_housing.tar.gz启动rpc服务
主要有三种启动配置:
- 使用cpu+xpu部署,使用Paddle-Lite xpu优化加速能力;
- 单独使用cpu部署,使用Paddle-Lite优化加速能力;
- 使用cpu部署,不使用Paddle-Lite加速。
推荐使用前两种部署方式。
启动rpc服务,使用cpu+xpu部署,使用Paddle-Lite xpu优化加速能力
python3 -m paddle_serving_server.serve --model uci_housing_model --thread 6 --port 9292 --use_lite --use_xpu --ir_optim启动rpc服务,使用cpu部署, 使用Paddle-Lite加速能力
python3 -m paddle_serving_server.serve --model uci_housing_model --thread 6 --port 9292 --use_lite --ir_optim启动rpc服务,使用cpu部署, 不使用Paddle-Lite加速能力
python3 -m paddle_serving_server.serve --model uci_housing_model --thread 6 --port 9292client调用
from paddle_serving_client import Client
import numpy as np
client = Client()
client.load_client_config("uci_housing_client/serving_client_conf.prototxt")
client.connect(["127.0.0.1:9292"])
data = [0.0137, -0.1136, 0.2553, -0.0692, 0.0582, -0.0727,
-0.1583, -0.0584, 0.6283, 0.4919, 0.1856, 0.0795, -0.0332]
fetch_map = client.predict(feed={"x": np.array(data).reshape(1,13,1)}, fetch=["price"])
print(fetch_map)其他说明
模型实例及说明
以下提供部分样例,其他模型可参照进行修改。
| 示例名称 | 示例链接 |
|---|---|
| fit_a_line | fit_a_line_xpu |
| resnet | resnet_v2_50_xpu |
注:支持昆仑芯片部署模型列表见链接。不同模型适配上存在差异,可能存在不支持的情况,部署使用存在问题时,欢迎以Github issue,我们会实时跟进。
昆仑芯片支持相关参考资料
File: doc/Run_On_XPU_EN.md
Paddle Serving Using Baidu Kunlun Chips
(English|简体中文)
Paddle serving supports deployment using Baidu Kunlun chips. Currently, it supports deployment on the ARM CPU server with Baidu Kunlun chips
(such as Phytium FT-2000+/64), or Intel CPU with Baidu Kunlun chips. We will improve
the deployment capability on various heterogeneous hardware servers in the future.
Install docker images
We recommend using the docker deployment service. In the xpu environment, you can refer to the Docker image document to install the xpu image, and further complete tasks such as construction, installation, and deployment.
Compilation and installation
Refer to compile document to setup the compilation environment. The following is based on FeiTeng FT-2000 +/64 platform.
Compilatiton
- Compile the Serving Server
cd Serving
mkdir -p server-build-arm && cd server-build-arm
cmake -DPYTHON_INCLUDE_DIR=/usr/include/python3.7m/ \
-DPYTHON_LIBRARIES=/usr/lib64/libpython3.7m.so \
-DPYTHON_EXECUTABLE=/usr/bin/python \
-DWITH_PYTHON=ON \
-DWITH_LITE=ON \
-DWITH_XPU=ON \
-DSERVER=ON ..
make -j10You can run make install to produce the target in ./output directory. Add -DCMAKE_INSTALL_PREFIX=./output to specify the output path to CMake command shown above. Please specify -DWITH_MKL=ON on Intel CPU platform with AVX2 support.
- Compile the Serving Client
mkdir -p client-build-arm && cd client-build-arm
cmake -DPYTHON_INCLUDE_DIR=/usr/include/python3.7m/ \
-DPYTHON_LIBRARIES=/usr/lib64/libpython3.7m.so \
-DPYTHON_EXECUTABLE=/usr/bin/python \
-DWITH_PYTHON=ON \
-DWITH_LITE=ON \
-DWITH_XPU=ON \
-DCLIENT=ON ..
make -j10- Compile the App
cd Serving
mkdir -p app-build-arm && cd app-build-arm
cmake -DPYTHON_INCLUDE_DIR=/usr/include/python3.7m/ \
-DPYTHON_LIBRARIES=/usr/lib64/libpython3.7m.so \
-DPYTHON_EXECUTABLE=/usr/bin/python \
-DWITH_PYTHON=ON \
-DWITH_LITE=ON \
-DWITH_XPU=ON \
-DAPP=ON ..
make -j10Install the wheel package
After the compilations stages above, the whl package will be generated in python/dist/ under the specific temporary directories.
For example, after the Server Compiation step,the whl package will be produced under the server-build-arm/python/dist directory, and you can run pip install -u python/dist/*.whl to install the package.
Request parameters description
In order to deploy serving
service on the arm server with Baidu Kunlun xpu chips and use the acceleration capability of Paddle-Lite,please specify the following parameters during deployment.
| param | param description | about |
|---|---|---|
| use_lite | using Paddle-Lite Engine | use the inference capability of Paddle-Lite |
| use_xpu | using Baidu Kunlun for inference | need to be used with the use_lite option |
| ir_optim | open the graph optimization | refer toPaddle-Lite |
Deplyment examples
Download the model
wget --no-check-certificate https://paddle-serving.bj.bcebos.com/uci_housing.tar.gz
tar -xzf uci_housing.tar.gzStart RPC service
There are mainly three deployment methods:
- deploy on the cpu server with Baidu xpu using the acceleration capability of Paddle-Lite and xpu;
- deploy on the cpu server standalone with Paddle-Lite;
- deploy on the cpu server standalone without Paddle-Lite.
The first two deployment methods are recommended.
Start the rpc service, deploying on cpu server with Baidu Kunlun chips,and accelerate with Paddle-Lite and Baidu Kunlun xpu.
python3 -m paddle_serving_server.serve --model uci_housing_model --thread 6 --port 9292 --use_lite --use_xpu --ir_optimStart the rpc service, deploying on cpu server,and accelerate with Paddle-Lite.
python3 -m paddle_serving_server.serve --model uci_housing_model --thread 6 --port 9292 --use_lite --ir_optimStart the rpc service, deploying on cpu server.
python3 -m paddle_serving_server.serve --model uci_housing_model --thread 6 --port 9292from paddle_serving_client import Client
import numpy as np
client = Client()
client.load_client_config("uci_housing_client/serving_client_conf.prototxt")
client.connect(["127.0.0.1:9292"])
data = [0.0137, -0.1136, 0.2553, -0.0692, 0.0582, -0.0727,
-0.1583, -0.0584, 0.6283, 0.4919, 0.1856, 0.0795, -0.0332]
fetch_map = client.predict(feed={"x": np.array(data).reshape(1,13,1)}, fetch=["price"])
print(fetch_map)Others
Model example and explanation
Some examples are provided below, and other models can be modifed with reference to these examples.
| sample name | sample links |
|---|---|
| fit_a_line | fit_a_line_xpu |
| resnet | resnet_v2_50_xpu |
Note:Supported model lists refer to doc. There are differences in the adaptation of different models, and there may be some unsupported cases. If you have any problem,please submit Github issue, and we will follow up in real time.
Kunlun chip related reference materials
File: doc/Save_CN.md
保存用于 Serving 部署的模型参数
背景介绍
模型参数信息保存在模型文件中,为什么还要保存用于 Paddle Serving 部署的模型参数呢,原因有3个:
- 服务化场景分为客户端和服务端,服务端加载模型,而在客户端没有模型信息,但需要在客户端需实现数据拼装和类型转换。
- 模型升级过程中
feed vars和fetch vars的名称变化会导致代码升级,通过增加一个alias_name字段映射名称,代码无需升级。 - 部署
Web服务,并使用URL方式访问时,请求信息中缺少类型和维度信息,在服务端推理前需要进行转换。
功能设计
飞桨训推一体框架中,从动态图模型训练到静态图推理部署,一体化流程如下所示
①动态图训练 → ②模型动转静 → ③静态模型 → ④模型保存 → ⑤Serving 部署在飞桨框架2.1对模型与参数的保存与载入相关接口进行了梳理,完整文档参考模型保存与载入
- 对于训练调优场景,我们推荐使用
paddle.save/load保存和载入模型; - 对于推理部署场景,我们推荐使用
paddle.jit.save/load(动态图)和paddle.static.save/load_inference_model(静态图)保存载入模型;
Paddle Serving 模型参数保存接口定位是在 ②模型动转静 导出 ③静态模型后,使用 paddle.static.load_inference_model 接口加载模型,和 paddle.static.save_vars 接口保存模型参数。
生成的模型参数信息保存在 paddle_serving_server/client.prototxt 文件中,其格式如下
feed_var {
name: "x"
alias_name: "image"
is_lod_tensor: false
feed_type: 1
shape: 3
shape: 960
shape: 960
}
fetch_var {
name: "save_infer_model/scale_0.tmp_1"
alias_name: "save_infer_model/scale_0.tmp_1"
is_lod_tensor: false
fetch_type: 1
shape: 1
shape: 960
shape: 960
}| 参数 | 描述 |
|---|---|
| name | 实际变量名 |
| alias_name | 变量别名,与 name 的关联业务场景中变量名 |
| is_lod_tensor | 是否为 LOD Tensor |
| feed_type | feed 变量类型 |
| fetch_type | fetch 变量类型 |
| shape 数组 | 变量的 Shape 信息 |
feed 与 fetch 变量的类型列表如下:
| 类型 | 类型值 |
|---|---|
| int64 | 0 |
| float32 | 1 |
| int32 | 2 |
| float64 | 3 |
| int16 | 4 |
| float16 | 5 |
| bfloat16 | 6 |
| uint8 | 7 |
| int8 | 8 |
| bool | 9 |
| complex64 | 10 |
| complex128 | 11 |
功能使用
Paddle 推理模型有3种形式,每种形式的读模型的方式都不同,散列方式必须以路径方式加载,其余2种采用目录或文件方式均可。
- Paddle 2.0前版本:
__model__,__params__ - Paddle 2.0后版本:
*.pdmodel,*.pdiparams - 散列:
__model__,conv2d_1.w_0,conv2d_2.w_0,fc_1.w_0,conv2d_1.b_0, ...
paddle_serving_client.convert 接口既支持 PYTHON 命令方式执行,又支持 代码中引入运行。
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
dirname |
str | - | 需要转换的模型文件存储路径,Program结构文件和参数文件均保存在此目录。 |
serving_server |
str | "serving_server" |
转换后的模型文件和配置文件的存储路径。默认值为serving_server |
serving_client |
str | "serving_client" |
转换后的客户端配置文件存储路径。默认值为serving_client |
model_filename |
str | None | 存储需要转换的模型Inference Program结构的文件名称。如果设置为None,则使用 __model__ 作为默认的文件名 |
params_filename |
str | None | 存储需要转换的模型所有参数的文件名称。当且仅当所有模型参数被保>存在一个单独的二进制文件中,它才需要被指定。如果模型参数是存储在各自分离的文件中,设置它的值为None |
一.PYTHON 命令执行
首先需要安装 paddle_serivng_client 包,以目录方式加载模型。
示例一,是以模型路径方式加载模型,适用于全部3种类型。
python3 -m paddle_serving_client.convert --dirname ./your_inference_model_dir示例二,以指定加载 当前路径 下模型 dygraph_model.pdmodel 和 dygraph_model.pdiparams,保存结果在 serving_server 和 serving_client 目录。
python3 -m paddle_serving_client.convert --dirname . --model_filename dygraph_model.pdmodel --params_filename dygraph_model.pdiparams --serving_server serving_server --serving_client serving_client二.代码引入执行
代码引入执行方式,通过 import io 包并调用 inference_model_to_serving 实现模型参数保存。
import paddle_serving_client.io as serving_io
serving_io.inference_model_to_serving(dirname, serving_server="serving_server", serving_client="serving_client", model_filename=None, params_filename=None)Serving 部署
生成完的模型可直接用于服务化推理,服务端使用和客户端使用。
一.服务端部署示例
示例一:C++ Serving 启动服务
python3 -m paddle_serving_server.serve --model serving_server --port 9393 --gpu_id 0示例二:Python Pipeline 启动服务,在 config.yml 中指定模型路径
op:
det:
#并发数,is_thread_op=True时,为线程并发;否则为进程并发
concurrency: 6
#当op配置没有server_endpoints时,从local_service_conf读取本地服务配置
local_service_conf:
#client类型,包括brpc, grpc和local_predictor.local_predictor不启动Serving服务,进程内预测
client_type: local_predictor
#det模型路径
model_config: ocr_det_model
#Fetch结果列表,以client_config中fetch_var的alias_name为准
fetch_list: ["save_infer_model/scale_0.tmp_1"]
# device_type, 0=cpu, 1=gpu, 2=tensorRT, 3=arm cpu, 4=kunlun xpu
device_type: 0二.客户端部署示例
通过 client 对象的 load_client_config 接口加载模型配置信息
from paddle_serving_client import Client
from paddle_serving_app.reader import Sequential, File2Image, Resize, CenterCrop
from paddle_serving_app.reader import RGB2BGR, Transpose, Div, Normalize
client = Client()
client.load_client_config(
"serving_client/serving_client_conf.prototxt")
client.connect(["127.0.0.1:9393"])
seq = Sequential([
File2Image(), Resize(256), CenterCrop(224), RGB2BGR(), Transpose((2, 0, 1)),
Div(255), Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225], True)
])
image_file = "daisy.jpg"
img = seq(image_file)
fetch_map = client.predict(feed={"inputs": img}, fetch=["save_infer_model/scale_0.tmp_0"])File: doc/Save_EN.md
How to save a servable model of Paddle Serving?
(简体中文|English)
Export from saved model files
you can use a build-in python module called paddle_serving_client.convert to convert it.
python -m paddle_serving_client.convert --dirname ./your_inference_model_dirIf you have saved model files using Paddle's save_inference_model API, you can use Paddle Serving's inference_model_to_serving API to convert it into a model file that can be used for Paddle Serving.
import paddle_serving_client.io as serving_io
serving_io.inference_model_to_serving(dirname, serving_server="serving_server", serving_client="serving_client", model_filename=None, params_filename=None )Arguments are the same as inference_model_to_serving API.
| Argument | Type | Default | Description |
|---|---|---|---|
dirname |
str | - | Path of saved model files. Program file and parameter files are saved in this directory. |
serving_server |
str | "serving_server" |
The path of model files and configuration files for server. |
serving_client |
str | "serving_client" |
The path of configuration files for client. |
model_filename |
str | None | The name of file to load the inference program. If it is None, the default filename __model__ will be used. |
params_filename |
str | None | The name of file to load all parameters. It is only used for the case that all parameters were saved in a single binary file. If parameters were saved in separate files, set it as None. |
Convert From Dynamic Graph
PaddlePaddle 2.0 provides a new dynamic graph mode, so here we use imagenet ResNet50 dynamic graph as an example to teach how to export from a saved model and use it for real online inference scenarios.
wget https://paddle-serving.bj.bcebos.com/others/dygraph_res50.tar #模型
wget https://paddle-serving.bj.bcebos.com/imagenet-example/daisy.jpg #示例输入(向日葵)
tar xf dygraph_res50.tar
python -m paddle_serving_client.convert --dirname . --model_filename dygraph_model.pdmodel --params_filename dygraph_model.pdiparams --serving_server serving_server --serving_client serving_client```
We can see that the `serving_server` and `serving_client` folders hold the server and client configuration of the model respectively
Start the server (GPU)python -m paddle_serving_server.serve --model serving_server --port 9393 --gpu_id 0
Client (`test_client.py`)from paddle_serving_client import Client
from paddle_serving_app.reader import Sequential, File2Image, Resize, CenterCrop
from paddle_serving_app.reader import RGB2BGR, Transpose, Div, Normalize
client = Client()
client.load_client_config(
"serving_client/serving_client_conf.prototxt")
client.connect(["127.0.0.1:9393"])
seq = Sequential([
File2Image(), Resize(256), CenterCrop(224), RGB2BGR(), Transpose((2, 0, 1)),
Div(255), Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225], True)
])
image_file = "daisy.jpg"
img = seq(image_file)
fetch_map = client.predict(feed={"inputs": img}, fetch=["save_infer_model/scale_0.tmp_0"])
print(fetch_map["save_infer_model/scale_0.tmp_0"].reshape(-1))
Runpython test_client.py
You can see that the prediction has been successfully executed. The above is the content predicted by the dynamic graph ResNet50 model on Serving. The use of other dynamic graph models is similar.
## Save from training or prediction script (Static Graph Mode)
Currently, paddle serving provides a save_model interface for users to access, the interface is similar with `save_inference_model` of Paddle.
``` python
import paddle_serving_client.io as serving_io
serving_io.save_model("imdb_model", "imdb_client_conf",
{"words": data}, {"prediction": prediction},
fluid.default_main_program())imdb_model is the server side model with serving configurations. imdb_client_conf is the client rpc configurations.
Serving has a dictionary for Feed and Fetch variables for client to assign. In the example, {"words": data} is the feed dict that specify the input of saved inference model. {"prediction": prediction} is the fetch dic that specify the output of saved inference model. An alias name can be defined for feed and fetch variables. An example of how to use alias name
is as follows:
from paddle_serving_client import Client
import sys
client = Client()
client.load_client_config(sys.argv[1])
client.connect(["127.0.0.1:9393"])
for line in sys.stdin:
group = line.strip().split()
words = [int(x) for x in group[1:int(group[0]) + 1]]
label = [int(group[-1])]
feed = {"words": words, "label": label}
fetch = ["acc", "cost", "prediction"]
fetch_map = client.predict(feed=feed, fetch=fetch)
print("{} {}".format(fetch_map["prediction"][1], label[0]))File: doc/Serving_Auth_Docker_CN.md
[Binary file]
2. Official Technical Reference & Guides (PaddlePaddle/docs)
File: README.md
PaddlePaddle docs
Source files for contents presented at PaddlePaddle documentation.
Note: English version API docs are generally docstrings in PaddlePaddle/Paddle, documents for other PaddlePaddle projects are being managed in their respective ways.
Codebase structure
- docs: PaddlePaddle 2.0 & above docs source file.
- docs/api: PaddlePaddle API docs.
- docs/guides: PaddlePaddle guides docs.
- docs/tutorial: PaddlePaddle tutorial docs.
- ci_scripts: docs CI scripts.
How to build
- pre-requirements
- docker
- Instructions
- step1: clone docstext
git clone https://github.com/PaddlePaddle/docs - step2: build docstext
cd docs mkdir output bash docs-build.sh -f absolute_path_docs - step3: preview docs
The output of docs will be generated in docs/output.
- step1: clone docs
How to contribute
PaddlePaddle welcomes documentation contributions, please see CONTRIBUTING.md for details.
License
File: CONTRIBUTING.md
Contributing
Since the open source of PaddlePaddle, we have provided high-quality Chinese and English documents. There are also many developers who have made important contributions to the improvement of the quality of the documentation. Thanks very much for every developer's support for PaddlePaddle documentation.
Introduction
We very much welcome you to participate in the construction of PaddlePaddle documentation and work with us to improve the quality of PaddlePaddle documentation. At present, PaddlePaddle document is divided into the following parts, you can choose any part of your interest to participate:
- Guides
- Practice
- API Documentation
Guides
This part of the content is mainly a guide to the use of PaddlePaddle. You can correct or improve the existing content, or you can add documents that you think are important. We very much welcome your suggestions and modifications regarding the use of the guides document.
Practice
The Practice is mainly to use PaddlePaddle for specific case implementation. At present, many developers have contributed very good cases, such as OCR recognition, face key-point detection, etc. We welcome you to submit your project to our repo, and finally show it on the official website of PaddlePaddle.
API Documentation
PaddlePaddle's API documentation contains an introduction to the API. We welcome you to propose changes to API documentation, whether it is typo or modification instructions and examples, we are very grateful for any contributions you have made to the API documentation.
Participation
Guides
This part of the content is stored in the docs/docs/guides directory, you can make your changes by submitting a PR. For more information, please refer to: Document Contribution Guide.
Practice
This part of the content is divided into two parts, the source code and the official website documentation. The source code is stored in the form of a notebook in book/paddle2.0_docs directory; after your notebook file is merged, we will convert it into an md file and store it in [docs/docs/tutorial](https: //github.com/PaddlePaddle/docs/tree/develop/docs/tutorial), and then presented to the official website. For more information, please refer to: [Call for Contribution] Tutorials for PaddlePaddle 2.0.
API Documentation
PaddlePaddle provides API documentation in both Chinese and English. The English API documentation is stored in the Paddle, you can modify English documents at this location; and Chinese API documents are stored in the docs/docs/api. You can fix and improve any errors and content in the document, or add content that you think is needed in the document. We are very grateful for all your contributions to the API document. For more information, please refer to: English API Documentation Contribution Guide, Chinese API Documentation Contribution Guide.
Submit PR
Any modification of PaddlePaddle documentation should be completed by submitting a PR. For more information, please refer to Submit PR.
File: CONTRIBUTING_cn.md
贡献文档
飞桨框架自开源以来,就提供了高质量的中英文文档。也有许多开发者为文档质量的提升,做出了重要的贡献,非常感谢每一位开发者对飞桨文档的支持。
文档说明
飞桨框架非常欢迎你参与到飞桨文档的建设中,与我们一同提升飞桨文档的质量。目前,飞桨文档分为以下几个部分,你可以选择任意你感兴趣的部分来参与:
- 使用教程
- 应用实践
- API 文档
使用教程
这部分内容主要是对飞桨框架的使用指南的说明,你可以对现有的内容进行纠错或者是改进,也可以新增你认为重要的文档在这个栏目中。我们非常欢迎你提出任何关于使用教程文档的建议以及修改。
应用实践
应用实践主要是使用飞桨框架进行具体的案例实现。目前已经有许多开发者贡献了非常优秀的案例,如 OCR 识别、人脸关键点检测等,我们非常欢迎你提交你的项目到我们的 repo 中来,并最终呈现在飞桨的官网上。
API 文档
API 文档是飞桨框架的 API 文档,包含了飞桨框架 API 的说明介绍。我们非常欢迎你对我们的 API 文档提出修改,不管是 typo 或者是修改说明与示例,我们都非常感谢你对于 API 文档所作出的任何贡献。
参与方式
使用教程
这部分内容存放在 docs/docs/guides 目录下,你可以通过提交 PR 的方式,来作出你的修改。具体修改方式请参考:文档贡献指南。
应用实践
这部分内容存放于 docs/practices 目录下。我们非常欢迎你提交基于飞桨框架的实践案例(以 .ipynb notebook 格式),包括但不限于计算机视觉、自然语言处理、推荐系统等方向。提交后会呈现在官方文档的应用实践中。具体贡献方式请参考文档贡献指南。
API 文档
飞桨框架同时提供中英文 API 文档。其中,英文 API 文档存于 Paddle 源代码中,绝大部分通过官网文档的源代码即可链接到,你可以在此位置对英文文档进行修改;而中文 API 文档存放在 docs/docs/api 目录下。你可以针对文档中的任何错误与内容进行修复与完善,或者是新增你认为该文档中所需要的内容,我们非常感谢你对于 API 文档所付出的一切。具体修改方式请参考:英文 API 文档贡献指南、中文 API 文档贡献指南。
提交 PR
你对于飞桨文档的任何修改,都应该通过提交 PR 的方式来完成,具体的方法可以参考提交 PR。
File: README_cn.md
PaddlePaddle docs
docs 是 PaddlePaddle 官网文档 的源文件。
注意:英文版 API 文档直接从PaddlePaddle/Paddle 的 docstring 中生成,飞桨其他项目的文档分别在其对应的位置中管理。
仓库结构
- docs: 飞桨框架 2.0 以及之后版本文档的源文件。
- docs/api: 飞桨中文 API 文档的源文件。
- docs/guides: 飞桨官方教程的源文件。
- docs/tutorial: 飞桨相关案例的源文件。
- ci_scripts: docs CI 相关的文件。
如何构建文档
- 依赖
- docker
- 构建过程
- step1: clone docstext
git clone https://github.com/PaddlePaddle/docs - step2: build docstext
cd docs mkdir output bash docs-build.sh -f absolute_path_docs - step3: preview docs
输出的文件会保存在 docs/output 路径下。
- step1: clone docs
贡献
我们非常欢迎你贡献文档!你可以参考 贡献指南 直接参与。
License
File: README_ja.md
PaddlePaddle docs
PaddlePaddle ドキュメントで紹介されている内容のソースファイルです。
注: 英語版 API ドキュメントは一般的に PaddlePaddle/Paddle のドキュメントです。他の PaddlePaddle プロジェクトのドキュメントはそれぞれの方法で管理されています。
コードベースの構造
- docs: PaddlePaddle 2.0 以上のドキュメントソースファイル。
- docs/api: PaddlePaddle API ドキュメント。
- docs/guides: PaddlePaddle のガイドドキュメント。
- docs/tutorial: PaddlePaddle チュートリアルのドキュメント。
- ci_scripts: ドキュメント CI スクリプト。
ビルド方法
- 事前条件
- docker
- 使用方法
- step1: clone docstext
git clone https://github.com/PaddlePaddle/docs - step2: build docstext
cd docs mkdir output bash docs-build.sh -f absolute_path_docs - step3: preview docs
docs の出力は docs/output に生成されます。
- step1: clone docs
コントリビュート方法
詳細は CONTRIBUTING.md をご覧ください。
ライセンス
File: .pre-commit-config.yaml
repos:
Common hooks
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:- id: check-merge-conflict
- id: check-symlinks
- id: detect-private-key
files: (?!.paddle)^.$ - id: end-of-file-fixer
types: [text] - id: trailing-whitespace
types: [text]
- repo: https://github.com/Lucas-C/pre-commit-hooks
rev: v1.5.1
hooks:- id: remove-crlf
types: [text] - id: remove-tabs
types: [text]
- id: remove-crlf
- repo: https://github.com/PFCCLab/typos-pre-commit-mirror.git
rev: v1.48.0
hooks:- id: typos
args: [--force-exclude]
- id: typos
Document hooks
- repo: https://github.com/PFCCLab/dochooks
rev: v0.6.0
hooks:- id: insert-whitespace-between-cn-and-en-char
files: .md$|.rst$ - id: check-case-conflict
- id: insert-whitespace-between-cn-and-en-char
For Python files
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.16.0
hooks:- id: ruff-check
args: [--fix, --exit-non-zero-on-fix, --no-cache]
types_or: [python, pyi] - id: ruff-format
types_or: [python, pyi, jupyter]
- id: ruff-check
For YAML files
- repo: https://github.com/PFCCLab/yamlfmt-pre-commit-mirror.git
rev: v0.21.0
hooks:- id: yamlfmt
File: ci_scripts/api_white_list.txt
paddle/distributed/init_parallel_env_cn.rst
paddle/distributed/spawn_cn.rst
paddle/distributed/ReduceOp_cn.rst
paddle/distributed/scatter_cn.rst
paddle/distributed/all_gather_cn.rst
paddle/distributed/all_reduce_cn.rst
paddle/distributed/reduce_cn.rst
paddle/distributed/barrier_cn.rst
paddle/distributed/broadcast_cn.rst
paddle/distributed/split_cn.rst
paddle/distributed/fleet/Fleet_cn.rst
paddle/distributed/fleet/utils/HDFSClient_cn.rst
paddle/distributed/fleet/utils/LocalFS_cn.rst
paddle/DataParallel_cn.rst
paddle/distributed/ParallelEnv_cn.rst
paddle/device/is_compiled_with_xpu_cn.rst
paddle/static/xpu_places_cn.rst
paddle/device/XPUPlace_cn.rst
paddle/utils/cpp_extension/load_cn.rst
paddle/utils/cpp_extension/setup_cn.rst
paddle/utils/cpp_extension/CppExtension_cn.rst
paddle/utils/cpp_extension/CUDAExtension_cn.rst
paddle/hub/Overview_cn.rst
paddle/incubate/autograd/Overview_cn.rst
File: ci_scripts/CAPItools/README.md
CAPI tools
CAPI tools 用于一键生成 C++ 的 rst 文档。
调用方式
python main.py <source dir> <target dir>若不设置source dir和target dir,则默认先查找已安装的paddlepaddle包环境。
其中:
- source dir 是安装后的 Paddle C++ API 声明路径。 例如
venv/Lib/site-packages/paddle/include/paddle。 - target dir 目标文件保存路径。
最终生成结果如下所示:
target dir
| -cn
|- index.rst
|- Paddle
|- fluid
|- phi
|- ...
| -en
|- index.rst
|- Paddle
|- fluid
|- phi
|- ...获取最新 PaddlePaddle
pip install python -m pip install paddlepaddle==0.0.0 -f https://www.paddlepaddle.org.cn/whl/windows/cpu-mkl-avx/develop.html
代码结构
`main.py`文件主要用于处理和筛选包文件, 并调用`utils_helper.py`中的函数进行文件生成
def analysis_file() # 用于解析文件内容(多线程不安全)
def generate_docs() # 用于创建目录并传值给 utils_helper.py 中的函数进行文件生成
def cpp2py() # 用于筛选出 cpp api 和 py api 相对应的函数名称`utils_helper.py`文件主要存放函数生成、解析, 以及文件写入的工作
class func_helper(object) # 用于生成和解析方法
decode() # 用于解析输出输出参数、函数名称、返回值、函数注释信息
class class_helper(object) # 用于生成和解析类
decode() # 同 func_helper()
def generate_overview() # 用于生成 overview.rst 文件File: ci_scripts/CAPItools/requirements.txt
robotpy-cppheaderparser==5.1.0
paddle
File: docs/index_cn.rst
.. PaddlePaddle documentation master file, created by
sphinx-quickstart on Thu Jun 7 17:04:53 2018.
You can adapt this file completely to your liking, but it should at least
contain the root toctree directive.
###############
欢迎使用 Paddle
###############
.. toctree::
:maxdepth: 1
install/index_cn.rst
guides/index_cn.rst
hardware_support/index_cn.rst
practices/index_cn.rst
api/index_cn.rst
dev_guides/index_cn.rst
faq/index_cn.rst
release_note_cn.mdFile: docs/index_en.rst
PaddlePaddle
.. toctree::
:maxdepth: 1
install/index_en.rst
guides/index_en.rst
api/index_en.rst
dev_guides/index_en.rst
release_note_en.mdFile: docs/release_note_cn.md
[Binary file]
File: docs/release_note_en.md
3.1 Release Note
The PaddlePaddle framework version 3.2 has further enhanced its performance in large model training and inference, hardware adaptation, and support for mainstream large models and high-performance acceleration libraries.
- In terms of large model training, the PaddlePaddle framework has undergone upgrades in three aspects: computation, parallel strategy, and fault tolerance:
- From the perspective of basic computational performance, FlashMask V3, a sparse mask attention computation with overlapping storage and computation, is proposed to maximize the computational efficiency of Attention. Additionally, it also implements an efficient lossless training technique with FP8 mixed precision effect.
- At the level of distributed parallel strategy, a dynamically adaptive VRAM offloading strategy is proposed to achieve optimal balance between memory and computation. Combined with an innovatively designed VRAM-friendly pipeline parallel scheduling, it further reduces VRAM overhead.
- Enhanced the native fault tolerance capability of the framework, implemented a large-scale cluster training fault tolerance system, which can monitor online silent data corruption and other difficult-to-detect faults without affecting training efficiency, and implemented a highly available checkpoint disaster recovery method to reduce the loss of interruption recovery.
- In terms of hardware adaptation, we have comprehensively upgraded the plug-in adaptation solution for CUDA-like chips.
In terms of device resource management and scheduling, as well as high-performance collective communication libraries, management interface upgrades and communication capability enhancements have been made for CUDA-like chips, with a particular emphasis on enhancing distributed communication capabilities, aligning XCCL with the various structures and functions of NCCL. - Added a registration mechanism for CUDA-like operators. Taking Muxi adaptation as an example, operator kernel registration can be completed with just one line of code based on the reuse of GPU operator kernels. According to statistical calculations, the reuse rate of operator kernels can reach up to 92%, significantly reducing hardware adaptation costs.
In terms of user experience, the focus has been placed on enhancing compatibility, encompassing the development of interfaces compatible with industry practices, compatibility with the SafeTensors model format, and compatibility with third-party high-performance acceleration libraries. - The newly added and modified development interfaces are compatible with industry practices, with a series of new APIs and aliases introduced, along with new parameter aliases and both proprietary and generic parameters.
- Fully compatible with the Safetensors model format. The newly added FlexCheckpoint mechanism supports automatic parameter re-sharding across distributed strategies and model structures, significantly reducing the cost of weight conversion and thereby enhancing the end-to-end training and inference development efficiency of large models.
- The system has systematically enhanced its interface compatibility and operator registration capabilities, enabling one-click import of high-performance acceleration libraries. These libraries can be directly reused in PaddlePaddle's model training and inference acceleration processes without requiring code modifications.
1. user experience
New features
- New APIs:
paddle.msort,paddle.ravel,paddle.nn.functional.dropout1d,paddle.Tensor.type_as,paddle.Tensor.requires_grad,paddle.view_as_complex,paddle.view_as_real,paddle.nn.Parameter,paddle.broadcast_shapes,paddle.range,paddle.as_tensor,paddle.scatter_reduce/scatter_reduce_,paddle.scatter_add,paddle.tensor,paddle.softmax,paddle.Tensor.softmax,paddle.rand_like,paddle.is_autocast_enabled,paddle.get_autocast_gpu_dtype,paddle.Tensor.repeat,paddle.permute. #74421,#74439,#74444,#74454,#74459,[#74491]( https://github.com/PaddlePaddle/Paddle/pull/74491 )[# 74466]( https://github.com/PaddlePaddle/Paddle/pull/74466 ),#74438,#74594,#74542,#74694,#74564,#74540,#74586,#74651,#74807,#74632,#74834,#74952,#74772,#74441,#74561,#74525 - Added a series of APIs under
paddle.compat.*to support common usage in the industry and facilitate code migration, includingpaddle.compat.median,paddle.compat.nanmedian,paddle.compat.softmax,paddle.compat.sort,paddle.compat.split,paddle.compat.min/max, andpaddle.compat.Unfold. #74865, #74874 - Added a series of initialization APIs to support commonly used parameter initialization methods in the industry, including
paddle.nn.init.kaiming_uniform_,paddle.nn.init.xavier_uniform_,paddle.nn.init.uniform_,paddle.nn.init.kaiming_normal_,paddle.nn.init.xavier_normal_,paddle.nn.init.normal_,paddle.nn.init.calculate_gain,paddle.nn.init.constant_,paddle.nn.init.dirac_,paddle.nn.init.eye_,paddle.nn.init.ones_,paddle.nn.init.orthogonal_,paddle.nn.init.trunc_normal_, andpaddle.nn.init.zeros_. #74478 - Added usage of parameter aliases in API, allowing for more flexible input options such as
xorinput. This includes functions likepaddle.maximum,paddle.minimum,paddle.sqrt,paddle.topk,paddle.polar,paddle.stack,paddle.cos,paddle.floor,paddle.log,paddle.pow,paddle.rsqrt,paddle.sign,paddle.sin,paddle.multiply, andpaddle.where. #74683, #74795, #74887, #74592 paddle.Tensornow supports multiple initialization methods, enabling flexible Tensor creation. #74619, #75022, #75065- The API has added some proprietary parameters to enhance existing functions, including
paddle.nn.functional.gelu,paddle.divide/div/div_,paddle.add,paddle.Tensor.copy_,paddle.norm,paddle.linalg.norm,paddle.nn.functional.silu, andpaddle.repeat_interleave. #74485, #74562, #74420, #74768, #74855, #74903, #74788, #74631, #74947 - The API has added some common parameters:
out,device,dtype,requires_grad,pin_memory, andbias, enhancing the existing functionality. These includepaddle.zeros,paddle.zeros_like,paddle.ones,paddle.ones_like,paddle.arange,paddle.eye,paddle.empty,paddle.empty_like,paddle.full,paddle.full_like,paddle.randn,paddle.Tensor.new_full,paddle.Tensor.new_empty,paddle.Tensor.new_ones,paddle.Tensor.new_zeros,paddle.tril/triu,paddle.bmm,paddle.nn.Conv1D/Conv2D/Conv3D/Embedding,paddle.diff,paddle.cumsum,paddle.var,paddle.multinomial, andpaddle.mean. #74477,#74526,#74711,#74582,#74624,#74849,#74612,#74875,#74641,#74949,#74918,#74914,#74934,#74920,#74955,#74226,#74946 - Added aliases to APIs to support more calling methods. These include
paddle.Tensor.mul_/mul,paddle.autograd.Function,paddle.argwhere,paddle.cat,paddle.clamp,paddle.ger,paddle.take_along_dim,paddle.linalg.matmul,paddle.special.logsumexp,paddle.concatenate,paddle.eq/gt,paddle.Tensor.take_along_dim, andpaddle.nn.Conv1d/Conv2d/Conv3d, etc. #74493, #74569, #74870
Bug fixes
- Fixed the precision issue of
paddle.nanmedianin PaddlePaddle. #74263 - Fixed the issue of
paddle.distributed.fleet.utils.hybrid_parallel_util.fused_allreduce_gradientsin 0-D scenarios. #74957 - Fixed the issue of
paddle.matmulin distributed mode. #74989
Enhanced functionality
- For scenarios involving the return of multiple Tensor objects, the experience has been optimized through encapsulation using the Paddle data structure, including
paddle.topk.#74931 - Create a class API to support the usage of variable-sized parameters. #74494
Documents
Other
- Optimization related to code style. #74654,#74655,#74665,#74660,#74667,#74664,#74662,#74661,#74658,#74657,#74666,#74659,#74663,#74656,#74673,#74672,#74671,#74674,#74675,#74670,#74669,#74677,#74709,#74714,#74712,#74713,#74704,#74746,#74748,#74743,#74742,#74744,#74745,#74747,#74794,#74789,#74793,#74786,#74791,#74787,#74827,#74608,#74288,#74287,#74385,#74395,#74475,#74647
- Optimization related to MKLDNN/ONEDNN. #74299,#74244,#74230,#74314,#74327,#74325,#74326,#74315,#74399,#74398,#74393,#74392,#74367,#74391,#74423,#74424,#74436,#74417,#74410,#74473,#74458,#74501,#74487,#74502,#74513,#74518,#74516,#74507,#74504,#74505,#74509,#74535,#74536,#74517,#74503,#74557,#74550,#74575,#74587,#74576,#74588,#74549,#74581,#74583,#74628,#74630,#74635,#74679,#74648,#74127,#74636,#74552,#74551,#74678,#74680,#74730,#74751,#74895,#74821,#74897,#74734
- Optimizations related to code implementation, variable and file renaming. #74309, #74597, #74613, #74376, #74479, #74960, #74968, #74977
- Optimizations related to unit tests, and bug fixes for unit test issues. #74595
- Compilation-related optimizations and CI issue fixes. #74356, #74936
- Optimize debugging and printing information, and optimize error reporting information. #74765, #74381, #74384, #74386, #74387, #74383, #74519, #74520, #74468
- Optimizations related to custom operators. #74402
- Distributed FlexCheckpoint support. #74966, #74593, #74785, #74814
2. Basic execution architecture
New features
- Support for dynamic graphs. #74484
- Support for safetensors. #74642, #74609, #75049
- Added offloader to optimize computation efficiency. #74837
- Added API support for forward computation of conv_transpose. #74431
- Added offloader to optimize computation efficiency. #74837
- The inference deployment has added w4afp8 quantization inference, supporting w4afp8 quantization weight pure permutation and all2all communication #74270
Bug fixes
- Core framework and infrastructure optimization. #74336, #74554, #74634
- Calculation accuracy and type handling. #74278, #74222, #74830
- Optimization of dynamic dimension check logic. #74633, #74650
- Memory and illegal access fixes. #74347, #73443, #74953
- Fixed printing of error/warning messages. #74474, #74533, #74685, #74721, #74754
- Code quality and documentation correction. #74378, #74828
- Fixed the processing logic of the flashmask API. #74928
- Fixed the issue where splitting CudaGraph subgraphs did not take effect in dynamic-to-static mode. (#74749)
Enhanced functionality
- C++ extension development. #74338
- Optimization of FlexCP function. #74752, #74981
- Optimize memory allocation. #74463
Deprecated
- Clean up old IR-related unit tests for dynamic, static, and transition scenarios. #74698, #74715, #74718, #74782, #74962
Other
- Update patch version. #74940
3. Distributed & automatic parallelism
Parallel strategy
In version 3.2, we have made multiple enhancements to the pipeline parallelism feature, including implementing support for dictionary parameter passing and extending the compatibility of Pipeline Layer and SharedLayerDesc with non-pipeline parallelism. Additionally, we have fixed several critical issues, such as IPC API exceptions for large-sized tensors, evaluation batches and non-computational losses in pipeline parallelism, gradient release errors in MoE models, hang issues caused by NCCL communication reconstruction in PP scenarios, and event management errors in dual-pipeline parallelism. Furthermore, we have conducted various performance optimizations, improved the computation overlap efficiency of dual-pipeline parallelism to enhance training performance, and upgraded the clear_param_storage method to support the clearing and resetting operations of multiple color collections in sharding mode.
New Features
- Implement support for dictionary parameter passing in Pipeline Parallel. #74574, #74867
- Pipeline Layer and SharedLayerDesc support non-pipeline parallelism (nonpp parallel). #74573
Bug fixes
- Fixed the IPC API issue with large-sized tensors. #74472
- Fixed issues related to evaluation batch and non-compute_loss in pipeline parallelism. #74170
- Fixed the gradient release issue on MoE model. #74972
- Fixed the hang issue when rebuilding NCCL comm in the pp scenario. #73625
- Fixed the event management error in dual pipeline parallelism (dual pp). #74158
Optimization and improvement
- Optimize the efficiency of computation overlap in parallel dual pipelines to enhance training performance. #74527
- Upgrade the clear_param_storage method to support the clearing and resetting of multiple color collections under sharding. #74741
Automatic parallelism
Functional improvements
- Support the default splitting derivation rule for the same dimension of distributed tensors when it is split by multiple mesh dimensions. #74396
- Improved the slicing derivation rule of the
reshapeoperator to support scenarios where the same dimension of a distributed tensor is sliced by multiple mesh dimensions. #74352, #74579, #74565 - Support changing the mesh of a tensor without altering the distributed tensor data. #74248
Bug fixes
- Fixed the bug of repeatedly creating communication groups when calling the
get_groupmethod ofProcessMesh. #73099 - Fixed the bug in the
get_local_slicesmethod in the MoE scenario. #74705 - Fixed the bug of gradient clipping in the MoE scenario. #74916
- Fixed the bug where the
stop_gradientparameter could not be passed between different stages in the pipeline parallel scenario. #73459 - Fixed the accuracy bug of gradient clipping in parallel pipeline scenarios. #74409
- Fixed the bug of generating redundant outputs in the dynamic graph pipeline parallel scenario. #74913
- Fixed the bug that the operators
moe_combineandmoe_gate_dispatchdid not work in the MoE scenario. #74645
Other
- Support accuracy alignment for manual and automatic parallelism of data loaders. #73941
- Optimize the dynamic graph pipeline parallel scheduling logic. #74720
Communication Library
In version 3.2, we fixed an error in DeepEP's support for sm90 compilation, added a pre-allocation function to the video memory allocation requested by DeepEP, and upgraded its intranode and internode computation kernels, further optimizing performance and stability.
Bug fixes
- Fixed a bug in DeepEP support for sm90 compilation. #74762
Functional improvements
- Added pre-allocation function for the GPU memory allocation requested by DeepEP. #74465
- Upgraded the intranode and internode computation kernels of DeepEP. #74284
4. Operator mechanism
New features
- API compatibility support. #74506, #74676, #74558, #74572, #74691, #74703, #74750, #74757, #74802, #74546, #74547, #74802, #74859, #74910, #74873, #74882, #74901, #74899, #74449
- Added fused_partial_rope operator. #74577
Bug fixes
- 0-size Tensor related fixes. #74295, #74305, #74323, #74354
- Major Tensor-related fixes. #74242, #74293, #74289, #74279, #74330, #74329, #74342, #74369, #74370, #74404, #74537, #74451, #74172, #74324, #74964, #74360, #74379, #74377, #74380, #74362, #74197
- API compatibility-related fixes. #74764, #74869, #74935
- [Open Source Task] Investigate and resolve precision issues in Paddle CPU/GPU Kernels. #74149, #74598, #74719, #74625, #74555
- Other important fixes. #74282, #74313, #74303, #74306, #74298, #74044, #74290, #74348, #74364, #74332, #74224, #74382, #74406, #74434, #74448, #74457, #74322, #74530, #74716, #74839, #74842, #74854, #74919, #74767, #75003
Enhanced functionality
- Improved API compatibility. #74456, #74480, #74523, #74490, #74548, #74596, #74568, #74559, #74629, #74623, #74700, #74643, #74602, #74783, #74781, #74735, #74725, #74815, #74856, #74925, #74545, #74932, #74784
- Slice/stride related optimizations. #74731, #74740, #74769, #74810, #74841, #74954, #74888, #74944, #74312, #74291, #74271, #74320, #74344, #74727, #74637
- Operator optimization and CUDA support. #74693, #74922, #74967
- Improved debugging information and compatibility enhancements. #74372, #74622
- Operator function expansion and optimization. #74790, #74979
Performance optimization
- FP8 computation optimization. #74471, #74684, #74911
- Basic operator performance optimization. #74442, #74638
- Support fa3 variable-length sequence reverse computation and optimize forward API. #73831
- Added FlashMask V2 function. #74729
Documents
- Fixed issues with English documentation and copyright year. #74737
Other
- The WITH_XPU_FFT option is enabled by default on XPU hardware. #74699
5. Hardware adaptation
Improved CUDA-like hardware integration solution
- The CUDA-like hardware access solution supports the reuse of cuBlas kernels #74591,
- Fix known issues in the CUDA-like hardware access solution
#74397, #74411, #74428, #74877, #74939
Main warehouse supports multiple hardware for single testing
New Custom Device API Support
6. Installation environment
Bug fixes
- Fixed the bug in flashattent compilation cache. #74388
- Fixed the bug where site.USER_SITE was None. #74373
- Fixed the compilation bug of gtest in multi-architecture Linux systems. #74723
- Fixed multiple compilation errors in DEBUG mode when WITH_GPU=ON. #74401
- Fixed the compilation bug of CUDA12.6 under Windows. #74990
- Fixed the bug in the api-benchmark baseline pipeline. #74770
- Fixed the bug in the api-benchmark baseline pipeline. #74778
- Fixed the bug in the api-benchmark baseline pipeline. #74779
- Fixed the bug in the api-benchmark baseline pipeline. #74780
- Fixed the bug in the api-benchmark baseline pipeline. #74800
- Fixed the bug in the api-benchmark baseline pipeline. #74803
Other
- Disable the test_custom_contiguous unit test. #74337
- Support for timed triggering of baseline tasks in the slice pipeline. #74419
- Support manually specifying the pr for adding slice recording baselines. #74445
- Check if there are any issues in the code. #74460
- Support CI PaddleX tasks on XPU. #74426
- Support slice pipeline exemption mechanism. #74482
- Updated the Paddle base image. #73423
- Fixed Ninja version 1.11 for Windows. #74590
- Support adding the ability to close PRs and cancel CIs. #74604
- Support for quickly skipping all CI. #74696
- Add an api-benchmark baseline pipeline. #74690
- Update the nccl version. #74809
- Update the RD list for the approve pipeline. #74838
- Update the RD list for the approve pipeline. #74902
- Update safetensor to the mirror. #74904
- Added the compilation flag for flashatten. #74959
- Temporarily disable the win-inference pipeline. #74980
- Support for compiling phi dynamic libraries on Windows. #74950
7. List of contributors
AIbin, Ayakouji, baiyue, baoqiwen, Chang Lu, Chen Zhiyang, co63oc, cyberslack_lee, cyy536, datutu-L, Deng Haodong, Difer, Eddie-Wang, enzodechine, fangfangssj, feri, fxyfxy777, ggggxm, GoldPancake, gouzil, Gu Shiwei, Haze188 灏喆, hohdiy, hong, HU Shenwei, huangjiyi, HydrogenSulfate, kjagsdq, LCStayingdullCircuit, Leo Guo, lightbrother, liufengwei0103, liuruyan, LiYuRio, LLSGYN, Lucas, Luckycheng222, lzy, Nana, Nyakku Shigure, ooo oo, Qianyue He, risemeup1, Ruibiao Chen, Ryan, Shuhao Liang, sneaxiy, Starrysea996, SUN Dong, Tao Luo, Tian, tianhaodongbd, tianshuo78520a, umiswing, waliwali777, wanghuancoder, Wenhao.Dai, wyw, XiaoguangHu, xiaoguoguo626807, xingmingyyj, Yichen Zhang, Yohanna, yongqiangma, Yuan Xiaolan, YUNSHEN XIE, Yuntao Nie, Yuqiang Ge, Yutian Rao, Zero Rains, Zhan Rongrui, Zhang Ting, zhanghonggeng, Zhaowu Pan, zhengshengning, ZhenxingLi, Zhou Xin, zhupengyang, zhwesky2010, Zichao, zty-king, Zx, zyfncg, zzm, 周周周, 正在学习, 苍天荒
File: docs/api/index_cn.rst
================== API 文档
欢迎使用飞桨框架(PaddlePaddle),PaddlePaddle 是一个易用、高效、灵活、可扩展的深度学习框架,致力于让深度学习技术的创新与应用更简单。
在本版本中,飞桨框架对 API 做了许多优化,您可以参考下表来了解飞桨框架最新版的 API 目录结构与说明。更详细的说明,请参见 版本说明 <../release_note_cn.html>_ 。此外,您可参考 PaddlePaddle 的 GitHub <https://github.com/PaddlePaddle/Paddle>_ 了解详情。
注: paddle.fluid.*、paddle.dataset.* 已废弃。
+--------------------------+------------------------------------------------------------------------------------+
| 目录 | 功能和包含的 API |
+==========================+====================================================================================+
| paddle.* | paddle |
| | 根目录下保留了常用 API 的别名,包括:paddle.tensor、 |
| | paddle.framework、paddle.device 目录下的所有 API。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.tensor | Tensor 操作相关的 API,包括 创建 zeros, |
| | 矩阵运算 matmul,变换 concat,计算 add,查找 argmax 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.framework | 框架通用 API 和动态图模式的 API,包括 no_grad、 |
| | save、load 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.amp | 自动混合精度策略,包括 auto_cast、 |
| | GradScaler 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.audio | 语音领域 API, 包括特征提取、数据集操作等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.autograd | 自动求导相关 API,包括 backward、PyLayer 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.callbacks | 日志回调类,包括 ModelCheckpoint、 |
| | ProgBarLogger 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.compat | PyTorch 兼容的函数与模块, |
| | 行为与 PyTorch 对应接口一致 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.cuda | PyTorch 兼容的函数与模块, |
| | 包含与 CUDA 设备相关的函数和模块 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.device | 设备管理相关 API,包括 set_device、get_device 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.distributed | 分布式相关基础 API。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.distributed.fleet | 分布式相关高层 API。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.distribution | 概率分布类 API,包括常用的各种概率分布操作。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.fft | 快速傅里叶变换的相关 API,包括 fft、fft2 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.geometric | 图学习领域 API,包括消息传递和图采样等操作。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.hub | 模型拓展相关的 API,包括 list、load、help 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.incubate | 飞桨新增功能的孵化目录,实验性 API。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.io | 数据输入输出相关 API,包括 Dataset、DataLoader 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.jit | 动态图转静态图相关 API,包括 to_static、 |
| | not_to_static、save、load 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.linalg | 线性代数相关 API,包括 det、svd 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.metric | 评估指标计算相关的 API,包括 Accuracy、Auc 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.nn | 组网相关的 API,包括 Linear、卷积 Conv2D、 |
| | 循环神经网络 RNN、损失函数 CrossEntropyLoss、 |
| | 激活函数 ReLU 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.onnx | paddle 转换为 onnx 协议相关 API,包括 export 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.optimizer | 优化算法相关 API,包括 SGD,Adagrad、Adam 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.optimizer.lr | 学习率衰减相关 API,包括 NoamDecay、StepDecay、 |
| | PiecewiseDecay 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.profiler | 飞桨框架的性能分析器,提供对模型训练和推理过程的性能数据进行展示和统计分析的功能。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.random | 随机数生成相关 API,包括 initial_seed 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.regularizer | 正则化相关 API,包括 L1Decay、L2Decay 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.signal | 信号处理领域 API。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.special | paddle.special 模块是模仿 SciPy 的 special 模块设计的,包含了许多特殊数学函数。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.static | 静态图下基础框架相关 API,包括 Variable、Program、 |
| | Executor 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.static.nn | 静态图下组网专用 API,包括 全连接层 fc、控制流 |
| | while_loop/cond。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.sysconfig | Paddle 系统路径相关 API,包括 get_include、get_lib 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.text | NLP 领域 API,包括 NLP 领域相关的数据集, |
| | 如 Imdb、Movielens。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.utils | 工具类相关 API,包括 CppExtension、CUDAExtension 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.vision | 视觉领域 API,包括 数据集 Cifar10、数据处理 |
| | ColorJitter、常用基础网络结构 ResNet 等。 |
+--------------------------+------------------------------------------------------------------------------------+
| paddle.sparse | 稀疏领域的 API。 |
+--------------------------+------------------------------------------------------------------------------------+
File: docs/api/index_en.rst
================== API Reference
PaddlePaddle (PArallel Distributed Deep LEarning) is an efficient, flexible, and extensible deep learning framework, commits to making the innovation and application of deep learning technology easier.
In this version, PaddlePaddle has made many optimizations to the APIs. You can refer to the following table to understand the API directory structure and description of the latest version of PaddlePaddle.In addition, you can refer to PaddlePaddle's GitHub <https://github.com/PaddlePaddle/Paddle>_ for details, or read Release Notes <../release_note_en.html>_ to learn about the features of the new version.
The API directory structure of PaddlePaddle is as follows:
+--------------------------+----------------------------------------------------------------+
| Directory | Functions and Included APIs |
+==========================+================================================================+
| paddle.* | The aliases of commonly used APIs are reserved in the |
| | paddle root directory, which currently include all |
| | the APIs in the paddle.tensor, paddle.framework and |
| | paddle.device directories. |
+--------------------------+----------------------------------------------------------------+
| paddle.tensor | APIs related to tensor operations such as creating |
| | zeros, matrix operation matmul, transforming concat, |
| | computing add, and finding argmax. |
+--------------------------+----------------------------------------------------------------+
| paddle.framework | PaddlePaddle universal APIs and dynamic graph APIs |
| | such as no_grad, save and load. |
+--------------------------+----------------------------------------------------------------+
| paddle.amp | Paddle automatic mixed precision strategy, including |
| | auto_cast, GradScaler, etc. |
+--------------------------+----------------------------------------------------------------+
| paddle.audio | Audio API, including feature extraction and dataset |
| | operations. |
+--------------------------+----------------------------------------------------------------+
| paddle.autograd | Auto grad APIs, including backward, PyLayer, etc. |
+--------------------------+----------------------------------------------------------------+
| paddle.callbacks | Paddle log callback APIs, including ModelCheckpoint, |
| | ProgBarLogger, etc. |
+--------------------------+----------------------------------------------------------------+
| paddle.compat | PyTorch-compatible APIs, with identical calling methods |
| | and behaviors to their PyTorch counterparts. |
+--------------------------+----------------------------------------------------------------+
| paddle.cuda | PyTorch-compatible APIs, |
| | including CUDA-related utilities |
+--------------------------+----------------------------------------------------------------+
| paddle.device | Device management related APIs, such as set_device, |
| | get_device, etc. |
+--------------------------+----------------------------------------------------------------+
| paddle.distributed | Distributed related basic APIs. |
+--------------------------+----------------------------------------------------------------+
| paddle.distributed.fleet | Distributed related high-level APIs. |
+--------------------------+----------------------------------------------------------------+
| paddle.distribution | Probability distribution class APIs, including various common |
| | probability distribution. |
+--------------------------+----------------------------------------------------------------+
| paddle.fft | Fast Fourier Transform related APIs, such as |
| | fft, fft2, etc. |
+--------------------------+----------------------------------------------------------------+
| paddle.geometric | APIs for Graph Learning, including message passing, |
| | graph sampling, etc. |
+--------------------------+----------------------------------------------------------------+
| paddle.hub | Model extension API, including list, load, help, etc. |
+--------------------------+----------------------------------------------------------------+
| paddle.incubate | APIs for incubating new features. |
+--------------------------+----------------------------------------------------------------+
| paddle.io | APIs related to data input and output such as |
| | Dataset, and DataLoader. |
+--------------------------+----------------------------------------------------------------+
| paddle.inference | APIs related to inference for predictions. |
+--------------------------+----------------------------------------------------------------+
| paddle.jit | Dynamic graph to static graph APIs, including |
| | to_static, not_to_static, save, load, etc. |
+--------------------------+----------------------------------------------------------------+
| paddle.linalg | Linear algebra related APIs, such as det, svd, etc. |
+--------------------------+----------------------------------------------------------------+
| paddle.metric | APIs related to evaluation computation such as |
| | Accuracy and Auc. |
+--------------------------+----------------------------------------------------------------+
| paddle.nn | Networking-related APIs such as Linear, Conv2D, |
| | CrossEntropyLoss, RNN,and ReLU, etc. |
+--------------------------+----------------------------------------------------------------+
| paddle.onnx | APIs related to convert paddle model to ONNX,such as |
| | export |
+--------------------------+----------------------------------------------------------------+
| paddld.optimizer | APIs related to optimization algorithms such as SGD, |
| | Adagrad, and Adam. |
+--------------------------+----------------------------------------------------------------+
| paddle.optimizer.lr | APIs related to learning rate decay, such as |
| | NoamDecay, StepDecay, PiecewiseDecay, etc. |
+--------------------------+----------------------------------------------------------------+
| paddle.profiler | Performance profiler APIs for the Paddle framework, |
| | providing functionality to display and analyze |
| | performance for model training and inference processes. |
+--------------------------+----------------------------------------------------------------+
| paddle.random | Random number generation related APIs, including initial_seed. |
+--------------------------+----------------------------------------------------------------+
| paddle.quantization | Quantization related APIs. |
+--------------------------+----------------------------------------------------------------+
| paddle.regularizer | Regularization APIs, including L1Decay, L2Decay, etc. |
+--------------------------+----------------------------------------------------------------+
| paddle.signal | APIs for signal processing. |
+--------------------------+----------------------------------------------------------------+
| paddle.sparse | The Sparse domain API. |
+--------------------------+----------------------------------------------------------------+
| paddle.static | Basic framework related APIs under static graph, |
| | such as Variable, Program, Executor, etc. |
+--------------------------+----------------------------------------------------------------+
| paddle.static.nn | Special APIs for networking under static graph such |
| | as full connect layer fc and control flow |
| | while_loop/cond. |
+--------------------------+----------------------------------------------------------------+
| paddle.sysconfig | System configuration APIs, such as get_include, get_lib. |
+--------------------------+----------------------------------------------------------------+
| paddle.text | The NLP domain API currently includes data sets |
| | related to the NLP domain, such as Imdb and Movielens. |
+--------------------------+----------------------------------------------------------------+
| paddle.utils | Utils APIs, including CppExtension, CUDAExtension. |
+--------------------------+----------------------------------------------------------------+
| paddle.vision | Vision domain APIs such as datasets Cifar10, |
| | data processing ColorJitter, and commonly used models |
| | like resnet. |
+--------------------------+----------------------------------------------------------------+
File: docs/api/paddle/_assert_cn.rst
.. _cn_api_paddle__assert:
_assert
.. py:function:: paddle._assert(condition, message="")
对 Python assert 的封装,支持符号追踪。
在动态图模式下,该函数的行为与 Python 的 assert 语句一致。在静态图模式下,当 condition 是 Tensor 时,会在计算图中创建一个 Assert 算子。
参数
::::::::::::
- condition (bool|Tensor) - 断言的条件。如果是 Tensor,必须是布尔标量(numel=1)。
- message (str,可选) - 断言失败时显示的错误信息。默认值为 ""。
代码示例
::::::::::::
.. code-block:: pycon
>>> import paddle
>>> # Non-tensor condition
>>> paddle._assert(1 == 1, "This should pass")
>>> # Tensor condition
>>> x = paddle.to_tensor([True])
>>> paddle._assert(x, "Tensor assertion")File: docs/api/paddle/abs__cn.rst
.. cn_api_paddle_abs:
abs\_
.. py:function:: paddle.abs_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_abs API,对输入 x 采用 Inplace 策略。
.. note::
别名支持: 参数名 input 可替代 x 。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/abs_cn.rst
.. _cn_api_paddle_abs:
abs
.. py:function:: paddle.abs(x, name=None)
绝对值函数。
.. math::
out = |x|
参数
:::::::::
- x (Tensor) - 输入的 Tensor,数据类型为:int32、int64、float16、float32、float64、complex64、complex128。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::
输出 Tensor,与 x 维度相同、数据类型相同。
代码示例
:::::::::
COPY-FROM: paddle.abs
File: docs/api/paddle/acos__cn.rst
.. cn_api_paddle_acos:
acos\_
.. py:function:: paddle.acos_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_acos API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/acos_cn.rst
.. _cn_api_paddle_acos:
acos
.. py:function:: paddle.acos(x, name=None, *, out=None)
arccosine 函数。
.. math::
out = cos^{-1}(x)
参数
:::::::::
- x (Tensor) - 输入的 Tensor,数据类型为:float32、float64、complex64、complex128。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
- out (Tensor,可选)- 输出的结果。该参数为仅关键字参数,默认值为 None。
返回
:::::::::
输出 Tensor,与 x 维度相同、数据类型相同。
代码示例
:::::::::
COPY-FROM: paddle.acos
File: docs/api/paddle/acosh__cn.rst
.. cn_api_paddle_acosh:
acosh\_
.. py:function:: paddle.acosh_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_acosh API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/acosh_cn.rst
.. _cn_api_paddle_acosh:
acosh
.. py:function:: paddle.acosh(x, name=None, *, out=None)
Arccosh 函数。
.. math::
out = acosh(x)
参数
:::::::::
- x (Tensor) - 输入的 Tensor,数据类型为:float32、float64、complex64、complex128。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
- out (Tensor,可选)- 输出的结果。该参数为仅关键字参数,默认值为 None。
返回
:::::::::
输出 Tensor,与 x 维度相同、数据类型相同。
代码示例
:::::::::
COPY-FROM: paddle.acosh
File: docs/api/paddle/add__cn.rst
.. cn_api_paddle_add:
add\_
.. py:function:: paddle.add_(x)
Inplace 版本的 :ref:cn_api_paddle_add API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/add_cn.rst
.. _cn_api_paddle_add:
add
.. py:function:: paddle.add(x, y, name=None, *, alpha=1, out=None)
逐元素相加算子,输入 x 与输入 y 逐元素相加,并将各个位置的输出元素保存到返回结果中。
.. note::
别名支持: 参数名 input 可替代 x,参数名 other 可替代 y ,如 add(input=tensor_x, other=tensor_y, ...) 等价于 add(x=tensor_x, y=tensor_y, ...) 。
输入 x 与输入 y 必须和广播为相同形状,关于广播规则,请参见 Tensor 介绍_ .
.. _Tensor 介绍: ../../guides/beginner/tensor_cn.html#id7等式为:
.. math::
Out = X + alpha \times Y
- :math:
X:多维 Tensor。 - :math:
Y:多维 Tensor。
以下情况使用该算子,该情况为:
X与Y的形状一样。Y的形状是X的一部分连续的形状。
参数
:::::::::
- x (Tensor) - 输入的 Tensor,数据类型为:bool、bfloat16、float16、float32、float64、int8、int16、int32、int64、uint8、complex64、complex128。
别名: input
- y (Tensor) - 输入的 Tensor,数据类型为:bool、bfloat16、float16、float32、float64、int8、int16、int32、int64、uint8、complex64、complex128。
别名: other
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
- alpha (Number, 可选) - 对 y 的缩放因子,默认值为 1。
- out (Tensor, 可选) - 输出 Tensor,默认值为 None。
返回
:::::::::
多维 Tensor,数据类型与 x 相同,维度为广播后的形状。
代码示例
:::::::::
COPY-FROM: paddle.add
File: docs/api/paddle/add_n_cn.rst
[Binary file]
File: docs/api/paddle/addmm__cn.rst
.. cn_api_paddle_addmm:
addmm\_
.. py:function:: paddle.addmm_(input, x, y, beta=1.0, alpha=1.0, name=None)
Inplace 版本的 :ref:cn_api_paddle_addmm API,对输入 input 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/addmm_cn.rst
[Binary file]
File: docs/api/paddle/addmv_cn.rst
.. _cn_api_paddle_addmv:
addmv
.. py:function:: paddle.addmv(input, mat, vec, beta=1, alpha=1, name=None, *, out=None)
执行矩阵 mat 和向量 vec 的矩阵-向量乘法,并将其加到输入 Tensor 上。
公式为:out = beta * input + alpha * (mat @ vec)
参数
:::::::::
- input (Tensor) - 待加的输入 Tensor。
- mat (Tensor) - 待乘的矩阵。
- vec (Tensor) - 待乘的向量。
- beta (float,可选) - input 的乘数,默认值为 1。
- alpha (float,可选) - mat @ vec 的乘数,默认值为 1。
- name (str,可选) - 操作名称,默认值为 None。
关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
:::::::::
Tensor:计算结果 Tensor。
代码示例
:::::::::
COPY-FROM: paddle.addmv
File: docs/api/paddle/addr_cn.rst
.. _cn_api_paddle_addr:
addr
.. py:function:: paddle.addr(input, vec1, vec2, beta=1, alpha=1, name=None, *, out=None)
执行向量 vec1 和向量 vec2 的外积,并将其加到输入矩阵上。
公式为:out = beta * input + alpha * (vec1 outer vec2)
参数
:::::::::
- input (Tensor) - 待加的输入 Tensor。
- vec1 (Tensor) - 第一个向量。
- vec2 (Tensor) - 第二个向量。
- beta (float,可选) - input 的乘数,默认值为 1。
- alpha (float,可选) - 外积的乘数,默认值为 1。
- name (str,可选) - 操作名称,默认值为 None。
关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
:::::::::
Tensor:计算结果 Tensor。
代码示例
:::::::::
COPY-FROM: paddle.addr
File: docs/api/paddle/all_cn.rst
.. _cn_api_paddle_all:
all
.. py:function:: paddle.all(x, axis=None, keepdim=False, name=None, *, out=None)
对指定维度上的 Tensor 元素进行逻辑与运算,并输出相应的计算结果。
.. note::
别名支持: 参数名 input 可替代 x, dim 可替代 axis。
参数
:::::::::
- x (Tensor)- 输入变量为多维 Tensor,数据类型为 bool、float32、float64、int32、int64。
别名: input
- axis (int | list | tuple,可选)- 计算逻辑与运算的维度。如果为 None,则计算所有元素的逻辑与并返回包含单个元素的 Tensor 变量,否则必须在 :math:[−rank(x),rank(x)] 范围内。如果 :math:axis [i] <0,则维度将变为 :math:rank+axis[i],默认值为 None。
别名: dim
- keepdim (bool,可选) - 是否在输出 Tensor 中保留减小的维度。除非 keepdim 为 True,否则输出 Tensor 的维度将比输入 Tensor 小一维,默认值为 False。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
- out (Tensor,可选) - 指定输出结果的 Tensor,默认值为 None。
返回
:::::::::
Tensor,在指定维度上进行逻辑与运算的 Tensor,数据类型和输入数据类型一致。
代码示例
:::::::::
COPY-FROM: paddle.all
File: docs/api/paddle/allclose_cn.rst
.. _cn_api_paddle_allclose:
allclose
.. py:function:: paddle.allclose(x, y, rtol=1e-05, atol=1e-08, equal_nan=False, name=None)
逐个检查 x 和 y 的所有元素是否均满足如下条件:
.. math::
\left| x - y \right| \leq atol + rtol \times \left| y \right|
该 API 的行为类似于 :math:numpy.allclose,即当两个待比较 Tensor 的所有元素均在一定容忍误差范围内视为相等则该 API 返回 True 值。
参数
::::::::::::
- **x** (Tensor) - 输入的 ``Tensor``,数据类型为:float16、float32、float64。别名 ``input``。
- **y** (Tensor) - 输入的 ``Tensor``,数据类型为:float16、float32、float64。别名 ``other``。
- **rtol** (float,可选) - 相对容忍误差,默认值为 1e-5。
- **atol** (float,可选) - 绝对容忍误差,默认值为 1e-8。
- **equal_nan** (bool,可选) - 如果设置为 True,则两个 NaN 数值将被视为相等,默认值为 False。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
计算得到的布尔类型单值 Tensor。
代码示例
::::::::::::
COPY-FROM: paddle.allclose
File: docs/api/paddle/amax_cn.rst
[Binary file]
File: docs/api/paddle/amin_cn.rst
[Binary file]
File: docs/api/paddle/angle_cn.rst
.. _cn_api_paddle_angle:
angle
.. py:function:: paddle.angle(x, name=None, *, out=None)
逐元素计算复数的相位角。对于非负实数,相位角为 0,而对于负实数,相位角为 :math:\pi。
.. math::
angle(x) = arctan2(x.imag, x.real)参数
:::::::::
- x (Tensor) - 输入的 Tensor,数据类型为:complex64, complex128 或 float32, float64。别名 input。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
:::::::::
输出实数 Tensor,与 x 的数值精度一致。
代码示例
:::::::::
COPY-FROM: paddle.angle
File: docs/api/paddle/any_cn.rst
.. _cn_api_paddle_any:
any
.. py:function:: paddle.any(x, axis=None, keepdim=False, name=None, *, out=None)
对指定维度上的 Tensor 元素进行逻辑或运算,并输出相应的计算结果。
.. note::
别名支持: 参数名 input 可替代 x,参数名 dim 可替代 axis,如 any(input=tensor_x, dim=1, ...) 等价于 any(x=tensor_x, axis=1, ...)。
参数
:::::::::
- x (Tensor) - 输入变量为多维 Tensor,数据类型为 bool、float32、float64、int32、int64。别名: input。
- axis (int|list|tuple,可选) - 计算逻辑或运算的维度。如果为 None,则计算所有元素的逻辑或并返回包含单个元素的 Tensor,否则必须在 :math:[−rank(x),rank(x)] 范围内。如果 :math:axis [i] <0,则维度将变为 :math:rank+axis[i],默认值为 None。别名: dim。
- keepdim (bool,可选) - 是否在输出 Tensor 中保留输入的维度。除非 keepdim 为 True,否则输出 Tensor 的维度将比输入 Tensor 小一维,默认值为 False。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
关键字参数
::::::::::::
- out (Tensor,可选) - 输出 Tensor。默认值为 None。
返回
:::::::::
Tensor,在指定维度上进行逻辑或运算的 Tensor,数据类型和输入数据类型一致。
代码示例
:::::::::
COPY-FROM: paddle.any
File: docs/api/paddle/arange_cn.rst
[Binary file]
File: docs/api/paddle/argmax_cn.rst
[Binary file]
File: docs/api/paddle/argmin_cn.rst
[Binary file]
File: docs/api/paddle/argsort_cn.rst
[Binary file]
File: docs/api/paddle/argwhere_cn.rst
.. _cn_api_paddle_argwhere:
argwhere
.. py:function:: paddle.argwhere(input)
返回输入 x 中非零元素的坐标。如果输入 x 有 n 维,共包含 z 个非零元素,返回结果是一个 shape 等于 [z x n] 的 Tensor,第 i 行代表输入中第 i 个非零元素的坐标。
参数
:::::::::
- **input** (Tensor)– 输入的 Tensor。返回
:::::::::
- Tensor(1-D Tensor),数据类型为 INT64 。
代码示例
:::::::::
COPY-FROM: paddle.argwhere
File: docs/api/paddle/as_complex_cn.rst
[Binary file]
File: docs/api/paddle/as_real_cn.rst
.. _cn_api_paddle_as_real:
as_real
.. py:function:: paddle.as_real(x, name=None)
将复数 Tensor 转为实数 Tensor。
输入 Tensor 的数据类型是 'complex64' 或者 'complex128',输出 Tensor 的数据类型相应为 'float32' 或者 'float64'。
输入 Tensor 的形状是 (*,) (其中 * 表示任意形状),输出 Tensor 的形状是 (*, 2),亦即,输出的形状是在输入形状后附加一个 2,因为一个复数的实部和虚部分别表示为一个实数。
下图展示了一个 as_real 简单的使用情形。一个形状为[2, 3]的复数 Tensor 经过 as_real 转换,拆分出一个长度为 2 的维度,形状变为[2, 3, 2]。
.. figure:: ../../images/api_legend/as_real.png
:alt: as_real 图示
:width: 500
:align: center
参数
:::::::::
- x (Tensor) - 输入 Tensor,数据类型为:'complex64' 或 'complex128'。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::
输出 Tensor,数据类型是 'float32' 或 'float64',与 x 的数值精度一致。
代码示例
:::::::::
COPY-FROM: paddle.as_real
File: docs/api/paddle/as_strided_cn.rst
[Binary file]
File: docs/api/paddle/as_tensor_cn.rst
.. _cn_api_paddle_as_tensor:
as_tensor
.. py:function:: paddle.as_tensor(data, dtype=None, device=None, requires_grad=False, pin_memory=False)
paddle.tensor 的别名,详细参考 :ref:cn_api_paddle_tensor。
File: docs/api/paddle/asin__cn.rst
.. cn_api_paddle_asin:
asin\_
.. py:function:: paddle.asin_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_asin API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/asin_cn.rst
.. _cn_api_paddle_asin:
asin
.. py:function:: paddle.asin(x, name=None)
arcsine 函数。
.. math::
out = sin^{-1}(x)
参数
::::::::::::
- **x** (Tensor) - 输入的 Tensor,数据类型为:float32, float64, float16, bfloat16,
uint8, int8, int16, int32, int64, complex64 or complex128。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
输出 Tensor,与 x 维度相同、数据类型相同(整数类型自动转换为 float32 类型)。
代码示例
::::::::::::
COPY-FROM: paddle.asin
File: docs/api/paddle/asinh__cn.rst
.. cn_api_paddle_asinh:
asinh\_
.. py:function:: paddle.asinh_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_asinh API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/asinh_cn.rst
.. _cn_api_paddle_asinh:
asinh
.. py:function:: paddle.asinh(x, name=None, *, out=None)
Arcsinh 函数。
.. math::
out = asinh(x)
参数
:::::::::
- x (Tensor) - 输入的 Tensor,数据类型为:float32、float64、complex64、complex128。别名 input。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
:::::::::
输出 Tensor,与 x 维度相同、数据类型相同。
代码示例
:::::::::
COPY-FROM: paddle.asinh
File: docs/api/paddle/assign_cn.rst
.. _cn_api_paddle_assign:
assign
.. py:function:: paddle.assign(x, output=None)
将输入数据拷贝至输出 Tensor。
参数
::::::::::::
- **x** (Tensor|np.ndarray|list|tuple|scalar) - 输入 Tensor,或 numpy 数组,或由基本数据组成的 list/tuple,或基本数据,支持数据类型为 float32、float64、int32、int64 和 bool。注意:由于当前框架的 protobuf 传输数据限制,float64 数据会被转化为 float32 数据。
- **output** (Tensor,可选) - 输出 Tensor。如果为 None,则创建一个新的 Tensor 作为输出 Tensor。默认值为 None。返回
::::::::::::
Tensor,形状、数据类型和值与 x 一致。
代码示例
::::::::::::
COPY-FROM: paddle.assign
File: docs/api/paddle/atan2_cn.rst
[Binary file]
File: docs/api/paddle/atan__cn.rst
.. cn_api_paddle_atan:
atan\_
.. py:function:: paddle.atan_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_atan API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/atan_cn.rst
.. _cn_api_paddle_atan:
atan
.. py:function:: paddle.atan(x, name=None, *, out=None)
arctangent 函数。
.. math::
out = tan^{-1}(x)
参数
::::::::::::
- **x** (Tensor) - 输入的 Tensor,数据类型为:float32、float64、float16、complex64、complex128。别名 ``input`` 。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
::::::::::::
输出 Tensor,与 x 维度相同、数据类型相同。
代码示例
::::::::::::
COPY-FROM: paddle.atan
File: docs/api/paddle/atanh__cn.rst
.. cn_api_paddle_atanh:
atanh\_
.. py:function:: paddle.atanh_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_atanh API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/atanh_cn.rst
.. _cn_api_paddle_atanh:
atanh
.. py:function:: paddle.atanh(x, name=None, *, out=None)
Arctanh 函数。
.. math::
out = atanh(x)
参数
:::::::::
- x (Tensor) - 输入的 Tensor,数据类型为:float32、float64、complex64、complex128。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
- out (Tensor,可选)- 输出的结果。该参数为仅关键字参数,默认值为 None。
返回
:::::::::
输出 Tensor,与 x 维度相同、数据类型相同。
代码示例
:::::::::
COPY-FROM: paddle.atanh
File: docs/api/paddle/atleast_1d_cn.rst
.. _cn_api_paddle_atleast_1d:
atleast_1d
.. py:function:: paddle.atleast_1d(*inputs, name=None)
将输入转换为张量并返回至少为 1 维的视图。标量输入会被转换, 1 维或更高维的输入则会被保留。
参数
::::::::::::
- **inputs** (Tensor|list(Tensor)) - 一个或多个 Tensor,支持可变参数用法,数据类型为: ``float16``, ``float32``, ``float64``, ``int16``, ``int32``, ``int64``, ``int8``, ``uint8``, ``complex64``, ``complex128``, ``bfloat16`` 或 ``bool``。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
Tensor 或者由 Tensor 组成的 list。当只有一个输入的时候返回一个 Tensor,当有多个输入的时候返回由 Tensor 组成的 list。
代码示例
::::::::::::
COPY-FROM: paddle.atleast_1d
File: docs/api/paddle/atleast_2d_cn.rst
.. _cn_api_paddle_atleast_2d:
atleast_2d
.. py:function:: paddle.atleast_2d(*inputs, name=None)
将输入转换为张量并返回至少为 2 维的视图。 2 维或更高维的输入会被保留。
下图分别展示了 atleast_2d 在不同数据类型下,对 1 个 0 维张量输入、1 个 0 维张量输入和 1 个 1 维张量输入,以及 1 个 0 维张量输入和 1 个 3 维张量输入,将其返回为至少为 2 维视图的张量或张量 list 的情形。
.. image:: ../../images/api_legend/atleast_2d.png
:width: 600
:alt: 图例
参数
::::::::::::
- **inputs** (Tensor|list(Tensor)) - 一个或多个 Tensor,支持可变参数用法,数据类型为: ``float16``, ``float32``, ``float64``, ``int16``, ``int32``, ``int64``, ``int8``, ``uint8``, ``complex64``, ``complex128``, ``bfloat16`` 或 ``bool``。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
Tensor 或者由 Tensor 组成的 list。当只有一个输入的时候返回一个 Tensor,当有多个输入的时候返回由 Tensor 组成的 list。
代码示例
::::::::::::
COPY-FROM: paddle.atleast_2d
File: docs/api/paddle/atleast_3d_cn.rst
.. _cn_api_paddle_atleast_3d:
atleast_3d
.. py:function:: paddle.atleast_3d(*inputs, name=None)
将输入转换为张量并返回至少为 3 维的视图。 3 维或更高维的输入会被保留。
参数
::::::::::::
- **inputs** (Tensor|list(Tensor)) - 一个或多个 Tensor,支持可变参数用法,数据类型为: ``float16``, ``float32``, ``float64``, ``int16``, ``int32``, ``int64``, ``int8``, ``uint8``, ``complex64``, ``complex128``, ``bfloat16`` 或 ``bool``。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
Tensor 或者由 Tensor 组成的 list。当只有一个输入的时候返回一个 Tensor,当有多个输入的时候返回由 Tensor 组成的 list。
代码示例
::::::::::::
COPY-FROM: paddle.atleast_3d
File: docs/api/paddle/autocast_cn.rst
.. _cn_api_paddle_autocast:
autocast
.. py:function:: paddle.autocast(device_type, dtype='float16', enabled=True, cache_enabled =True)
paddle.amp.autocast 的别名,请参考 :ref:cn_api_paddle_amp_autocast。
File: docs/api/paddle/baddbmm__cn.rst
.. cn_api_paddle_baddbmm:
baddbmm\_
.. py:function:: paddle.baddbmm_(input, x, y, beta=1.0, alpha=1.0, out_dtype=None, name=None)
Inplace 版本的 :ref:cn_api_paddle_baddbmm API,对输入 input 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/baddbmm_cn.rst
.. _cn_api_paddle_baddbmm:
baddbmm
.. py:function:: paddle.baddbmm(input, x, y, beta=1.0, alpha=1.0, out_dtype=None, name=None, *, out=None)
计算 x 和 y 的批量矩阵乘积,将结果乘以标量 alpha,再加上 input 与标量 beta 的乘积,得到输出。其中 input 与 x、y 乘积的维度必须是可广播的。
计算过程的公式为:
.. math::
out = \beta \times input + \alpha \times x \times y
其中 :math:\beta 和 :math:\alpha 是缩放因子。
.. note::
别名支持: 参数名 batch1 可替代 x,参数名 batch2 可替代 y ,如 baddbmm(input=tensor_input, batch1=tensor_x, batch2=tensor_y, ...) 等价于 baddbmm(input=tensor_input, x=tensor_x, y=tensor_y, ...) 。
参数
::::::::::::
- input (Tensor) - 输入 Tensor input,必须是一个 2 维或 3 维张量,数据类型支持 bfloat16、float16、float32、float64。
- x (Tensor) - 输入 Tensor x,必须是一个形状为 [b, n, p] 的 3 维张量,数据类型支持 bfloat16、float16、float32、float64。
别名:batch1
- y (Tensor) - 输入 Tensor y,必须是一个形状为 [b, p, m] 的 3 维张量,数据类型支持 bfloat16、float16、float32、float64。
别名:batch2
- beta (float,可选) - 乘以 input 的标量,数据类型支持 float,默认值为 1.0。
- alpha (float,可选) - 乘以 x*y 的标量,数据类型支持 float,默认值为 1.0。
- out_dtype (paddle.dtype, 可选) - 输出数据类型,默认值为 None,表示输出数据类型与输入 input 数据类型一致。支持设置为以下数据类型:float16、bfloat16、float32、float64。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
::::::::::::
计算得到的 Tensor。Tensor 数据类型与输入 input 数据类型一致。
代码示例
::::::::::::
COPY-FROM: paddle.baddbmm
File: docs/api/paddle/batch_cn.rst
.. _cn_api_paddle_batch:
batch
.. py:function:: paddle.batch(reader, batch_size, drop_last=False)
一个 reader 的装饰器。返回的 reader 将输入 reader 的数据打包成指定的 batch_size 大小的批处理数据(batched data)。
.. warning::
不推荐使用这个 API,如有数据加载需求推荐使用支持多进程并发加速的 paddle.io.DataLoader
参数
::::::::::::
- **reader** (generator)- 读取数据的数据 reader。
- **batch_size** (int)- 批尺寸。
- **drop_last** (bool) - 若设置为 True,则当最后一个 batch 不等于 batch_size 时,丢弃最后一个 batch;若设置为 False,则不会。默认值为 False。返回
::::::::::::
batched reader
代码示例
::::::::::::
COPY-FROM: paddle.batch
File: docs/api/paddle/bernoulli__cn.rst
.. cn_api_paddle_bernoulli:
bernoulli\_
.. py:function:: paddle.bernoulli_(x, p=0.5, name=None)
Inplace 版本的 :ref:cn_api_paddle_bernoulli API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
.. note::
参数名 ``input`` 可替代 ``x``,如 ``bernoulli_(input=tensor_x)`` 等价于 ``bernoulli_(x=tensor_x)``。File: docs/api/paddle/bernoulli_cn.rst
[Binary file]
File: docs/api/paddle/bincount_cn.rst
.. _cn_api_paddle_bincount:
bincount
.. py:function:: paddle.bincount(x, weights=None, minlength=0, name=None)
统计输入 Tensor 中每个元素出现的次数,如果传入 weights Tensor 则每次计数加一时会乘以 weights Tensor 对应的值。
参数
::::::::::::
- **x** (Tensor) - 输入 Tensor。必须是一维 Tensor,其中元素必须大于等于 0,数据类型为 int32, int64。别名 ``input`` 。
- **weights** (Tensor,可选) - weights Tensor,代表输入 Tensor 中每个元素的权重。长度必须与输入 Tensor 相同。数据类型为 int32, int64, float32 或 float64。默认为 None
- **minlength** (int,可选) - 输出 Tensor 的最小长度,如果大于输入 Tensor 中的最大值,则多出的位置补 0。该值必须大于等于 0。默认为 0。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
Tensor,维度为 1。
代码示例
::::::::::::
COPY-FROM: paddle.bincount
File: docs/api/paddle/binomial_cn.rst
.. _cn_api_paddle_binomial:
binomial
.. py:function:: paddle.binomial(count, prob, name=None)
以输入参数 count 和 prob 分别为二项分布的 n 和 p 参数,生成一个二项分布的随机数 Tensor ,支持 Tensor 形状广播。输出 Tensor 的 dtype 为 int64 。
.. math::
out_i \sim Binomial (n = count_i, p = prob_i)参数
::::::::::::
- **count** (Tensor) - Tensor 的每个元素代表一个二项分布的总试验次数。数据类型支持 ``int32`` 、``int64`` 。
- **prob** (Tensor) - Tensor 的每个元素代表一个二项分布的试验成功概率。数据类型支持 ``bfloat16`` 、``float16`` 、``float32`` 、``float64`` 。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
Tensor,二项分布采样得到的随机 Tensor,形状为 ``count`` 和 ``prob`` 进行广播后的 Tensor 形状, dtype 为 ``int64`` 。代码示例
::::::::::::
COPY-FROM: paddle.binomial
File: docs/api/paddle/bitwise_and__cn.rst
.. cn_api_paddle_bitwise_and:
bitwise\_and\_
.. py:function:: paddle.bitwise_and_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_bitwise_and API,对输入 x 采用 Inplace 策略。
参数
::::::::::::
- x (Tensor) - 输入的 Tensor。别名 input。
- y (Tensor) - 输入的 Tensor。别名 other。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/bitwise_and_cn.rst
.. _cn_api_paddle_bitwise_and:
bitwise_and
.. py:function:: paddle.bitwise_and(x, y, name=None, *, out=None)
对 Tensor x 和 y 逐元素进行 按位与 运算。
.. math::
Out = X & Y
.. note::
paddle.bitwise_and 遵守 broadcasting,如您想了解更多,请参见 Tensor 介绍_ .
.. _Tensor 介绍: ../../guides/beginner/tensor_cn.html#id7参数
::::::::::::
- x (Tensor)- 输入的 N-D Tensor,数据类型为:bool,uint8,int8,int16,int32,int64。别名 input。
- y (Tensor)- 输入的 N-D Tensor,数据类型为:bool,uint8,int8,int16,int32,int64。别名 other。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
关键字参数
::::::::::::
- out (Tensor,可选)- 输出的结果 Tensor,是与输入数据类型相同的 N-D Tensor。默认值为 None,此时将创建新的 Tensor 来保存输出结果。
返回
::::::::::::
按位与 运算后的结果 Tensor,数据类型与 x 相同。
代码示例
::::::::::::
COPY-FROM: paddle.bitwise_and
File: docs/api/paddle/bitwise_invert__cn.rst
.. cn_api_paddle_bitwise_invert:
bitwise\_invert\_
.. py:function:: paddle.bitwise_invert_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_bitwise_invert API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/bitwise_invert_cn.rst
.. _cn_api_paddle_bitwise_invert:
bitwise_invert
.. py:function:: paddle.bitwise_invert(x, out=None, name=None)
对 Tensor x 逐元素进行 按位取反 运算。
.. math::
Out = \sim X
.. note::
bitwise_invert 和 bitwise_not 执行相同的操作,功能等效。
参数
::::::::::::
- **x** (Tensor)- 输入的 N-D ``Tensor``,数据类型为:bool,uint8,int8,int16,int32,int64。
- **out** (Tensor,可选)- 输出的结果 ``Tensor``,是与输入数据类型相同的 N-D ``Tensor``。默认值为 None,此时将创建新的 Tensor 来保存输出结果。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
按位取反 运算后的结果 Tensor,数据类型与 x 相同。
代码示例
::::::::::::
COPY-FROM: paddle.bitwise_invert
File: docs/api/paddle/bitwise_left_shift__cn.rst
[Binary file]
File: docs/api/paddle/bitwise_left_shift_cn.rst
.. _cn_api_paddle_bitwise_left_shift:
bitwise_left_shift
.. py:function:: paddle.bitwise_left_shift(x, y, is_arithmetic=True, out=None, name=None)
对 Tensor x 和 y 逐元素进行 按位算术(或逻辑)左移 运算。
关于 有符号数的符号位 在不同情景下的行为:
- 算术左移时,符号位同其他位一样,一起左移,右边补 0;
- 逻辑左移时,符号位同其他位一样,一起左移,右边补 0;
- 算术右移时,符号位同其他位一样,一起右移,左边补符号位;
- 逻辑右移时,符号位同其他位一样,一起右移,左边补 0;
.. note::
当有符号数左移发生溢出时,其值不可控,可能会在左移时突然变号,这是因为在左移时,有符号数的符号位同样进行左移,会导致符号位右侧的值不断成为符号位,例如
example1:
.. code-block:: text
int8_t x = -45; // 补码为 1101,0011 表示-45
int8_t y = x << 2; //补码为 0100,1100 表示 76
int8_t z = x << 3; //补码为 1001,1000 表示-104
example2:
.. code-block:: text
int8_t x = -86; // 补码为 1010,1010 表示-86
int8_t y = x << 1; //补码为 0101,0100 表示 84
int8_t z = x << 2; //补码为 1010,1000 表示-88
以上为溢出导致的符号突变。.. math::
Out = X \ll Y
.. note::
paddle.bitwise_left_shift 遵守 broadcasting,如您想了解更多,请参见 Tensor 介绍_ .
.. _Tensor 介绍: ../../guides/beginner/tensor_cn.html#id7参数
::::::::::::
- **x** (Tensor)- 输入的 N-D ``Tensor``,数据类型为:uint8,int8,int16,int32,int64。别名 ``input``。
- **y** (Tensor)- 输入的 N-D ``Tensor``,数据类型为:uint8,int8,int16,int32,int64。别名 ``other``。
- **is_arithmetic** (bool) - 用于表明是否执行算术位移,True 表示算术位移,False 表示逻辑位移。默认值为 True,表示算术位移。
- **out** (Tensor,可选)- 输出的结果 ``Tensor``,是与输入数据类型相同的 N-D ``Tensor``。默认值为 None,此时将创建新的 Tensor 来保存输出结果。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
按位算术(逻辑)左移 运算后的结果 Tensor,数据类型与 x 相同。
代码示例 1
::::::::::::
算术左移
COPY-FROM: paddle.bitwise_left_shift:bitwise_left_shift_example1
代码示例 2
::::::::::::
逻辑左移
COPY-FROM: paddle.bitwise_left_shift:bitwise_left_shift_example2
File: docs/api/paddle/bitwise_not__cn.rst
.. cn_api_paddle_bitwise_not:
bitwise\_not\_
.. py:function:: paddle.bitwise_not_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_bitwise_not API,对输入 x 采用 Inplace 策略。
参数
::::::::::::
- x (Tensor) - 输入的 Tensor。别名 input。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/bitwise_not_cn.rst
.. _cn_api_paddle_bitwise_not:
bitwise_not
.. py:function:: paddle.bitwise_not(x, name=None, *, out=None)
对 Tensor x 逐元素进行 按位取反 运算。
.. math::
Out = \sim X
.. note::
paddle.bitwise_not 遵守 broadcasting,如您想了解更多,请参见 Tensor 介绍_ .
.. _Tensor 介绍: ../../guides/beginner/tensor_cn.html#id7参数
::::::::::::
- x (Tensor)- 输入的 N-D Tensor,数据类型为:bool,uint8,int8,int16,int32,int64。别名 input。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
关键字参数
::::::::::::
- out (Tensor,可选)- 输出的结果 Tensor,是与输入数据类型相同的 N-D Tensor。默认值为 None,此时将创建新的 Tensor 来保存输出结果。
返回
::::::::::::
按位取反 运算后的结果 Tensor,数据类型与 x 相同。
代码示例
::::::::::::
COPY-FROM: paddle.bitwise_not
File: docs/api/paddle/bitwise_or__cn.rst
.. cn_api_paddle_bitwise_or:
bitwise\_or\_
.. py:function:: paddle.bitwise_or_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_bitwise_or API,对输入 x 采用 Inplace 策略。
参数
::::::::::::
- x (Tensor) - 输入的 Tensor。别名 input。
- y (Tensor) - 输入的 Tensor。别名 other。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/bitwise_or_cn.rst
[Binary file]
File: docs/api/paddle/bitwise_right_shift__cn.rst
.. cn_api_paddle_bitwise_right_shift:
bitwise_right_shift\_
.. py:function:: paddle.bitwise_right_shift_(x, y, is_arithmetic=True, name=None)
Inplace 版本的 :ref:cn_api_paddle_bitwise_right_shift API,对输入 x 采用 Inplace 策略。
参数
::::::::::::
- **x** (Tensor)- 输入的 N-D ``Tensor``,数据类型为:uint8,int8,int16,int32,int64。别名 ``input``。
- **y** (Tensor)- 输入的 N-D ``Tensor``,数据类型为:uint8,int8,int16,int32,int64。别名 ``other``。
- **is_arithmetic** (bool) - 用于表明是否执行算术位移,True 表示算术位移,False 表示逻辑位移。默认值为 True,表示算术位移。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/bitwise_right_shift_cn.rst
[Binary file]
File: docs/api/paddle/bitwise_xor__cn.rst
.. cn_api_paddle_bitwise_xor:
bitwise_xor\_
.. py:function:: paddle.bitwise_xor_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_bitwise_xor API,对输入 x 采用 Inplace 策略。
参数
::::::::::::
- x (Tensor) - 输入的 Tensor。别名 input。
- y (Tensor) - 输入的 Tensor。别名 other。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/bitwise_xor_cn.rst
.. _cn_api_paddle_bitwise_xor:
bitwise_xor
.. py:function:: paddle.bitwise_xor(x, y, name=None, *, out=None)
对 Tensor x 和 y 逐元素进行 按位异或 运算。
.. math::
Out = X ^\wedge Y
.. note::
paddle.bitwise_xor 遵守 broadcasting,如您想了解更多,请参见 Tensor 介绍_ .
.. _Tensor 介绍: ../../guides/beginner/tensor_cn.html#id7参数
::::::::::::
- x (Tensor)- 输入的 N-D Tensor,数据类型为:bool,uint8,int8,int16,int32,int64。别名 input。
- y (Tensor)- 输入的 N-D Tensor,数据类型为:bool,uint8,int8,int16,int32,int64。别名 other。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
关键字参数
::::::::::::
- out (Tensor,可选)- 输出的结果 Tensor,是与输入数据类型相同的 N-D Tensor。默认值为 None,此时将创建新的 Tensor 来保存输出结果。
返回
::::::::::::
按位异或 运算后的结果 Tensor,数据类型与 x 相同。
代码示例
::::::::::::
COPY-FROM: paddle.bitwise_xor
File: docs/api/paddle/block_diag_cn.rst
.. _cn_api_paddle_block_diag:
block_diag
.. py:function:: paddle.block_diag(inputs, name=None)
根据输入的张量创建块对角矩阵。
本 API 支持两种调用方式:
Paddle 风格:
paddle.block_diag(inputs, name=None)
使用张量序列作为输入。PyTorch 风格:
paddle.block_diag(*tensors)
使用可变数量的张量参数。
参数
:::::::::
- inputs (list|tuple) - 张量列表或张量元组,其子项为 0、1、2 维的 Tensor。数据类型为: bool、 float16、 float32、 float64、 uint8、 int8、 int16、 int32、 int64、 bfloat16、 complex64、 complex128。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::
Tensor, 与 inputs 数据类型相同。
代码示例
:::::::::
COPY-FROM: paddle.block_diag
File: docs/api/paddle/bmm_cn.rst
.. _cn_api_paddle_bmm:
bmm
.. py:function:: paddle.bmm(x, y, name=None, *, out=None)
对输入 x 及输入 y 进行矩阵相乘。
两个输入的维度必须等于 3,并且矩阵 x 和矩阵 y 的第一维必须相等。同时矩阵 x 的第三维必须等于矩阵 y 的第二维。
例如:若 x 和 y 分别为 (b, m, k) 和 (b, k, n) 的矩阵,则函数的输出为一个 (b, m, n) 的矩阵。
参数
:::::::::
- **x** (Tensor) - 输入变量,类型为 Tensor。别名 ``input``。
- **y** (Tensor) - 输入变量,类型为 Tensor。别名 ``other``。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。关键字参数
:::::::::
- **out** (Tensor,可选) - 输出 Tensor,若不为 ``None``,计算结果将保存在该 Tensor 中,默认值为 ``None``。返回
:::::::::
Tensor,矩阵相乘后的结果。
代码示例
:::::::::
COPY-FROM: paddle.bmm
File: docs/api/paddle/broadcast_shape_cn.rst
.. _cn_api_paddle_broadcast_shape:
broadcast_shape
.. py:function:: paddle.broadcast_shape(x_shape, y_shape)
.. note::
该函数返回对 x_shape 大小的 Tensor 和 y_shape 大小的 Tensor 做 broadcast 操作后得到的 shape,如您想了解更多,请参见 Tensor 介绍_ .
.. _Tensor 介绍: ../../guides/beginner/tensor_cn.html#id7参数
:::::::::
- x_shape (list[int]|tuple[int]) - 输入 Tensor 的 shape。
- y_shape (list[int]|tuple[int]) - 输入 Tensor 的 shape。
返回
:::::::::
broadcast 操作后的 shape,返回类型为 list[int]。
代码示例
:::::::::
COPY-FROM: paddle.broadcast_shape
File: docs/api/paddle/broadcast_shapes_cn.rst
.. _cn_api_paddle_broadcast_shapes:
broadcast_shapes
.. py:function:: paddle.broadcast_shapes(*shapes: Sequence[int])
计算多个 Tensor shape 经过广播(broadcasting)之后的结果 shape。
参数
::::::::::::
- **shapes** (Sequence[int]) - 一个或多个 Tensor 的 shape。每个 shape 都是一个整数序列(List 或 Tuple)。返回
::::::::::::
list[int],广播后的结果 shape。
代码示例
::::::::::::
COPY-FROM: paddle.broadcast_shapes
File: docs/api/paddle/broadcast_tensors_cn.rst
[Binary file]
File: docs/api/paddle/broadcast_to_cn.rst
.. _cn_api_paddle_broadcast_to:
broadcast_to
.. py:function:: paddle.broadcast_to(x, shape, name=None)
根据 shape 指定的形状广播 x,广播后,x 的形状和 shape 指定的形状一致。
x 的维数和 shape 的元素数应小于等于 6,并且 shape 中的元素数应该大于等于 x 的维数。扩展的维度的维度值应该为 1。
下图展示了一个形状为[3]的一维张量根据 shape 指定的形状广播为[2,3]的二维张量这一过程。
.. figure:: ../../images/api_legend/broadcast_to.png
:width: 500
:align: center
.. note::
别名支持: 参数名 input 可替代 x 和 size 可替代 shape,如 input=tensor_x 等价于 x=tensor_x, size=[2, 3] 等价于 shape=[2, 3]。
参数
:::::::::
- **x** (Tensor) - 输入的 Tensor,数据类型为:bool、float16、float32、float64、int32、int64、uint8 或 uint16。
别名: ``input``
- **shape** (tuple|list|Tensor) - 给定输入 ``x`` 扩展后的形状,若 ``shape`` 为 list 或者 tuple,则其中的元素值应该为整数或者是形状为 1-D 或 0-D 的 Tensor,若 ``shape`` 类型为 Tensor,则其应该为 1-D Tensor。
别名: ``size``
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
:::::::::Tensor,数据类型与 x 相同。
代码示例
:::::::::
COPY-FROM: paddle.broadcast_to
File: docs/api/paddle/bucketize_cn.rst
.. _cn_api_paddle_bucketize:
bucketize
.. py:function:: paddle.bucketize(x, sorted_sequence, out_int32=False, right=False, name=None)
将根据给定的一维 Tensor sorted_sequence 返回输入 x 对应的桶索引。
参数
::::::::::
- x (Tensor) - 输入的 N 维 Tensor,支持的数据类型:int32、int64、float32、float64。
- sorted_sequence (Tensor) - 输入的一维 Tensor,支持的数据类型:int32、int64、float32、float64。该 Tensor 的数值在其最后一个维度递增。
- out_int32 (bool,可选) - 输出的数据类型支持 int32、int64。默认值为 False,表示默认的输出数据类型为 int64。
- right (bool,可选) - 根据给定 x 在 sorted_sequence 查找对应的上边界或下边界。如果 sorted_sequence 的值为 nan 或 inf,则返回最内层维度的大小。默认值为 False,表示在 sorted_sequence 的查找给定 x 的下边界。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
::::::::::
Tensor(与 x 维度相同),如果参数 out_int32 为 False,则返回数据类型为 int64 的 Tensor,否则将返回 int32 的 Tensor。
代码示例
::::::::::
COPY-FROM: paddle.bucketize
File: docs/api/paddle/cartesian_prod_cn.rst
[Binary file]
File: docs/api/paddle/cast__cn.rst
.. cn_api_paddle_cast:
cast\_
.. py:function:: paddle.cast_(x, dtype)
Inplace 版本的 :ref:cn_api_paddle_cast API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/cast_cn.rst
.. _cn_api_paddle_cast:
cast
.. py:function:: paddle.cast(x, dtype)
将 x 的数据类型转换为 dtype 并输出。支持输出和输入的数据类型相同。
下图展示了一个例子:将输入的 float64 类型 Tensor 转化为 uint8 类型 Tensor
.. image:: ../../images/api_legend/cast.png
:alt: 图例
参数
::::::::::::
- **x** (Tensor) - 输入多维 Tensor,支持的数据类型为:bool、float16、float32、float64、uint8、int32、int64。
- **dtype** (str|paddle.dtype|np.dtype) - 输出 Tensor 的数据类型。支持的数据类型为:bool、float16、float32、float64、int8、int32、int64、uint8。返回
::::::::::::
Tensor,维度与 x 相同,数据类型为 dtype。
代码示例
::::::::::::
COPY-FROM: paddle.cast
File: docs/api/paddle/cat_cn.rst
.. _cn_api_paddle_cat:
cat
.. py:function:: paddle.cat(x, axis=0, name=None, *, out=None)
concat 的别名,请参考 :ref:cn_api_paddle_concat。
File: docs/api/paddle/cauchy__cn.rst
.. cn_api_paddle_cauchy:
cauchy\_
.. py:function:: paddle.cauchy_(x, loc = 0, scale = 1, name = None)
直接修改输入张量 x,将所有元素替换为从柯西分布中随机采样的数值。
参数
::::::::::::
- **x** (Tensor) - 输入的 Tensor,支持的数据类型为:float32、float64。
- **loc** (scalar,可选) - 分布峰值的位置参数,数据类型为 float32 或 float64。默认值为 0,对应标准柯西分布。参数别名:median。
- **scale** (scalar,可选) - 表示分布峰值一半高度处的半宽度(HWHM),控制曲线的陡峭程度。必须为正数,数据类型为 float32 或 float64。默认值为 1,对应标准柯西分布。参数别名:sigma。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
Tensor,对输入的张量 x 直接进行了修改,数据类型与输入时相同。
代码示例
::::::::::::
COPY-FROM: paddle.cauchy_
File: docs/api/paddle/cdist_cn.rst
[Binary file]
File: docs/api/paddle/ceil__cn.rst
.. cn_api_paddle_ceil:
ceil\_
.. py:function:: paddle.ceil_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_ceil API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/ceil_cn.rst
.. _cn_api_paddle_ceil:
ceil
.. py:function:: paddle.ceil(x, name=None)
向上取整运算函数。
.. math::
out = \left \lceil x \right \rceil
.. note::
别名支持: 参数名 input 可替代 x,如 input=tensor_x 等价于 x=tensor_x。
参数
::::::::::::
- **x** (Tensor) - 输入的 Tensor,数据类型支持 float32, float64, float16, bfloat16, uint8, int8, int16, int32, int64。
别名: ``input``
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。
- **out** (Tensor,可选) - 指定输出结果的 ``Tensor``,默认值为 None。返回
::::::::::::
输出 Tensor,与 x 维度相同、数据类型相同。
代码示例
::::::::::::
COPY-FROM: paddle.ceil
File: docs/api/paddle/chunk_cn.rst
[Binary file]
File: docs/api/paddle/clamp__cn.rst
.. cn_api_paddle_clamp:
clamp\_
.. py:function:: paddle.clamp_(x, min=None, max=None, name=None)
clip_ 的别名,请参考 :ref:cn_api_paddle_clip_。
.. note::
别名支持:参数名 input 可替代 x,如 clamp_(input=tensor_x) 等价于 clamp_(x=tensor_x)。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/clamp_cn.rst
.. _cn_api_paddle_clamp:
clamp
.. py:function:: paddle.clamp(x, min=None, max=None, name=None, *, out=None)
clip 的别名,请参考 :ref:cn_api_paddle_clip。
File: docs/api/paddle/clamp_max_cn.rst
.. _cn_api_paddle_clamp_max:
clamp_max
.. py:function:: paddle.clamp_max(input, max, *, out=None)
将输入中的所有元素裁剪到区间 [min=None, max] 内。
该接口是 paddle.clip 的封装,仅设置上界。
参数
::::::::::::
- **input** (Tensor) - 输入的 Tensor。
- **max** (float|Tensor) - 裁剪的最大值。关键字参数
::::::::::::
- out (Tensor,可选) - 输出 Tensor。默认值为 None。
返回
::::::::::::
输出 Tensor,与 input 维度相同。
代码示例
::::::::::::
COPY-FROM: paddle.clamp_max
File: docs/api/paddle/clip__cn.rst
.. cn_api_paddle_clip:
clip\_
.. py:function:: paddle.clip_(x, min=None, max=None, name=None)
Inplace 版本的 :ref:cn_api_paddle_clip API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/clip_cn.rst
[Binary file]
File: docs/api/paddle/clone_cn.rst
.. _cn_api_paddle_clone:
clone
.. py:function:: paddle.clone(x, name=None)
对输入 Tensor :attr:x 进行拷贝,并返回一个新的 Tensor。
除此之外,该 API 提供梯度计算,在计算反向时,输出 Tensor 的梯度将会回传给输入 Tensor。
参数
:::::::::
- x (Tensor) - 输入 Tensor。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::
Tensor,从输入 :attr:x 拷贝的 Tensor。
代码示例
:::::::::
COPY-FROM: paddle.clone
File: docs/api/paddle/column_stack_cn.rst
.. _cn_api_paddle_column_stack:
column_stack
.. py:function:: paddle.column_stack(x, name=None)
沿水平轴堆叠输入 x 中的所有张量。 x 中的每个张量 tensor 如果在堆叠之前 tensor.ndim < 2 ,则首先被整形为 (tensor.numel(), 1)。所有张量必须具有相同的数据类型。
下图展示了一个 column_stack 的情形,将一个形状为(3,1)的二维张量与一个形状为(3,)的一维张量进行 column_stack 操作,其中一维张量首先被整形为(3,1),然后再沿水平轴堆叠输入所有张量。通过图例能很好看出张量的变化。
.. image:: ../../images/api_legend/column_stack.png
:width: 600
:alt: 图例
参数
::::::::::::
- **x** (list[Tensor]|tuple[Tensor]) - 输入 ``x`` 可以是张量的 list 或 tuple, ``x`` 中张量的数据类型必须相同。支持的数据类型: ``float16`` 、 ``float32`` 、 ``float64`` 、 ``int32`` 、 ``int64`` 或 ``bfloat16`` 。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
Tensor,与输入数据类型相同的堆叠张量。
代码示例
::::::::::::
COPY-FROM: paddle.column_stack
File: docs/api/paddle/combinations_cn.rst
[Binary file]
File: docs/api/paddle/complex_cn.rst
.. _cn_api_paddle_complex:
complex
.. py:function:: paddle.complex(real, imag, name=None, *, out=None)
给定实部和虚部,返回一个复数 Tensor。
参数
:::::::::
- real (Tensor) - 实部,数据类型为:float32 或 float64。
- imag (Tensor) - 虚部,数据类型和 real 相同。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
关键字参数
:::::::::
- **out** (Tensor,可选) - 输出 Tensor,若不为 ``None``,计算结果将保存在该 Tensor 中,默认值为 ``None``。返回
:::::::::
输出 Tensor,数据类型是 complex64 或者 complex128,与 real 和 imag 的数值精度一致。
.. note::
paddle.complex 遵守 broadcasting,如您想了解更多,请参见 Tensor 介绍_ .
.. _Tensor 介绍: ../../guides/beginner/tensor_cn.html#id7代码示例
:::::::::
COPY-FROM: paddle.complex
File: docs/api/paddle/concat_cn.rst
.. _cn_api_paddle_concat:
concat
.. py:function:: paddle.concat(x, axis=0, name=None, *, out=None)
对输入沿参数 axis 轴进行联结,返回一个新的 Tensor。该 API 不支持输入 0-D Tensor,因为其必须指定沿着某个轴拼接,而 0-D Tensor 没有轴。
下图展示了 concat 操作的典型情况——两个形状为 [2, 3, 4] 的三维张量通过 concat 操作沿着不同的 axis 轴拼接为不同形状的三维张量,我们可以清晰地看到不同维度拼接的效果。
.. image:: ../../images/api_legend/concat.png
:width: 500
:alt: 图例
.. note::
别名支持: 参数名 tensors 可替代 x,参数名 dim 可替代 axis ,如 concat(tensors=tensor_x, dim=1, ...) 等价于 concat(x=tensor_x, axis=1, ...) 。
参数
::::::::::::
- **x** (list|tuple) - 待联结的 Tensor list 或者 Tensor tuple,支持的数据类型为:bool、float16、bfloat16、float32、float64、int8、uint8、int16、uint16、int32、int64、complex64、complex128, ``x`` 中所有 Tensor 的数据类型应该一致。别名: ``tensors``。
- **axis** (int|Tensor,可选) - 指定对输入 ``x`` 进行运算的轴,可以是整数或者形状为[]的 0-D Tensor,数据类型为 int32 或者 int64。 ``axis`` 的有效范围是 [-R, R),R 是输入 ``x`` 中 Tensor 的维度,``axis`` 为负值时与 :math:`axis + R` 等价。默认值为 0。别名: ``dim``。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。关键字参数
:::::::::
- **out** (Tensor,可选) - 输出 Tensor,若不为 ``None``,计算结果将保存在该 Tensor 中,默认值为 ``None``。返回
::::::::::::
联结后的 Tensor,数据类型和 x 中的 Tensor 相同。
代码示例
::::::::::::
COPY-FROM: paddle.concat
File: docs/api/paddle/concatenate_cn.rst
.. _cn_api_paddle_concatenate:
concatenate
.. py:function:: paddle.concatenate(x, axis=0, name=None, *, out=None)
concat 的别名,请参考 :ref:cn_api_paddle_concat。
File: docs/api/paddle/conj_cn.rst
.. _cn_api_paddle_conj:
conj
.. py:function:: paddle.conj(x, name=None, *, out=None)
是逐元素计算 Tensor 的共轭运算。
参数
::::::::::::
- **x** (Tensor) - 输入的复数值的 Tensor,数据类型为:complex64、complex128、bfloat16、float16、float32、float64、int32 或 int64。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 ``None``。关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
::::::::::::
Tensor,输入的共轭。形状和数据类型与输入一致。如果 Tensor 元素是实数类型,如 float32、float64、int32、或者 int64,返回值和输入相同。
代码示例
::::::::::::
COPY-FROM: paddle.conj
File: docs/api/paddle/copysign__cn.rst
.. cn_api_paddle_copysign:
copysign\_
.. py:function:: paddle.copysign_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_copysign API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/copysign_cn.rst
.. _cn_api_paddle_copysign:
copysign
.. py:function:: paddle.copysign(x, y, name=None, *, out=None)
按照元素计算两个输入 Tensor 的 copysign 大小,由数值和符号组成,其数值部分来自于第一个 Tensor 中的元素,符号部分来自于第二个 Tensor 中的元素。
.. math::
copysign(x_{i},y_{i})=\left\{\begin{matrix}
& -|x_{i}| & if \space y_{i} <= -0.0\\
& |x_{i}| & if \space y_{i} >= 0.0
\end{matrix}\right.参数
::::::::::::
- **x** (Tensor) - 输入的复数值的 Tensor,数据类型为:bool, uint8, int8, int16, int32, int64, bfloat16, float16, float32, float64。别名: ``input``。
- **y** (Tensor) - 输入的复数值的 Tensor,数据类型为:bool, uint8, int8, int16, int32, int64, bfloat16, float16, float32, float64。别名: ``other``。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
::::::::::::
Tensor,输出数据类型与输入数据类型相同。
代码示例 1
::::::::::::
COPY-FROM: paddle.copysign:example1
代码示例 2
::::::::::::
支持广播机制
COPY-FROM: paddle.copysign:example2
代码示例 3
::::::::::::
y 为 +0.0 时
COPY-FROM: paddle.copysign:example_zero1
代码示例 4
::::::::::::
y 为 -0.0 时
COPY-FROM: paddle.copysign:example_zero2
File: docs/api/paddle/cos__cn.rst
.. cn_api_paddle_cos:
cos\_
.. py:function:: paddle.cos_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_cos API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/cos_cn.rst
.. _cn_api_paddle_cos:
cos
.. py:function:: paddle.cos(x, name=None, *, out=None)
余弦函数。
输入范围是 (-inf, inf),输出范围是 [-1,1]。
.. math::
out = cos(x)参数
::::::::::::
- **x** (Tensor) - 输入的 Tensor,数据类型为:float32、float64 、float16、complex64、complex128。别名 ``input``。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。关键字参数
:::::::::
- **out** (Tensor,可选) - 输出 Tensor,若不为 ``None``,计算结果将保存在该 Tensor 中,默认值为 ``None``。返回
::::::::::::
输出 Tensor,与 x 维度相同、数据类型相同。
代码示例
::::::::::::
COPY-FROM: paddle.cos
File: docs/api/paddle/cosh__cn.rst
.. cn_api_paddle_cosh:
cosh\_
.. py:function:: paddle.cosh_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_cosh API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/cosh_cn.rst
.. _cn_api_paddle_cosh:
cosh
.. py:function:: paddle.cosh(x, name=None, *, out=None)
双曲余弦函数。
输入范围是 (-inf, inf),输出范围是 [1,inf]。
.. math::
out = \frac{exp(x)+exp(-x)}{2}参数
::::::::::::
- **x** (Tensor) - 输入的 Tensor,数据类型为:float32、float64 、float16、complex64、complex128。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。
- **out** (Tensor,可选)- 输出的结果。该参数为仅关键字参数,默认值为 None。返回
::::::::::::
输出 Tensor,与 x 维度相同、数据类型相同。
代码示例
::::::::::::
COPY-FROM: paddle.cosh
File: docs/api/paddle/count_nonzero_cn.rst
.. _cn_api_paddle_count_nonzero:
count_nonzero
.. py:function:: paddle.count_nonzero(x, axis=None, keepdim=False, name=None)
沿给定的轴 axis 统计输入 Tensor x 中非零元素的个数。
参数
::::::::::
- x (Tensor) - 输入的 Tensor,数据类型为:bool、float16、float32、float64、int32、int64。别名:
input。 - axis (None|int|list|tuple,可选) - 指定对
x进行统计的轴。axis可以是 int 或 int 元素的列表/元组。axis值应该在范围[-D,D)内,D 是x的维度。如果axis或其中的元素值小于 0,则等价于 :math:axis + D。如果axis是 None,则对x的全部元素进行统计。默认值为 None。别名:dim。 - keepdim (bool,可选) - 是否在输出 Tensor 中保留被统计的维度。如果
keepdim为 True,则输出 Tensor 和x具有相同的维度(被统计的维度大小为 1);否则,输出 Tensor 会在axis上进行 squeeze 操作。默认值为 False。 - name (str,可选) - 具体用法请参见 :ref:
api_guide_Name,一般无需设置,默认值为 None。
返回
::::::::::
Tensor,沿着 axis 统计输入 Tensor 中非零元素的个数,数据类型 int64。
代码示例
::::::::::
COPY-FROM: paddle.count_nonzero
File: docs/api/paddle/CPUPlace_cn.rst
.. _cn_api_paddle_CPUPlace:
CPUPlace
.. py:class:: paddle.CPUPlace
CPUPlace 是一个设备描述符,指定 CPUPlace 则 Tensor 将被自动分配在该设备上,并且模型将会运行在该设备上。
代码示例
::::::::::::
COPY-FROM: paddle.CPUPlace
File: docs/api/paddle/create_parameter_cn.rst
.. _cn_api_paddle_create_parameter:
create_parameter
.. py:function:: paddle.create_parameter(shape,dtype,name=None,attr=None,is_bias=False,default_initializer=None)
创建一个参数。该参数是一个可学习的变量,拥有梯度并且可优化。
.. note::
这是一个低级别的 API。如果您希望自己创建新的 op,这个 API 将非常有用,无需使用 layers。
参数
::::::::::::
- **shape** (list[int]) - 指定输出 Tensor 的形状,它可以是一个整数列表。
- **dtype** (str|paddle.dtype|np.dtype) – 初始化数据类型。可设置的字符串值有:"float16","float32","float64"。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。
- **attr** (ParamAttr,可选) - 指定参数的属性对象。具体用法请参见 :ref:`cn_api_paddle_ParamAttr`。默认值为 None,表示将采用 ParamAttr 的默认方式初始化。
- **is_bias** (bool,可选) - 当 default_initializer 为空,该值会对选择哪个默认初始化程序产生影响。如果 is_bias 为真,则使用 initializer.Constant(0.0),否则使用 Xavier(),默认值 False。
- **default_initializer** (Initializer,可选) - 参数的初始化程序,默认值为空。返回
::::::::::::
创建的 Parameter 变量。
代码示例
::::::::::::
COPY-FROM: paddle.static.create_parameter
File: docs/api/paddle/crop_cn.rst
.. _cn_api_paddle_crop:
crop
.. py:function:: paddle.crop(x, shape=None, offsets=None, name=None)
根据偏移量(offsets)和形状(shape),裁剪输入(x)Tensor。
示例:
::
* 示例 1(输入为 2-D Tensor):
输入:
X.shape = [3, 5]
X.data = [[0, 1, 2, 0, 0],
[0, 3, 4, 0, 0],
[0, 0, 0, 0, 0]]
参数:
shape = [2, 2]
offsets = [0, 1]
输出:
Out.shape = [2, 2]
Out.data = [[1, 2],
[3, 4]]
* 示例 2(输入为 3-D Tensor):
输入:
X.shape = [2, 3, 4]
X.data = [[[0, 1, 2, 3],
[0, 5, 6, 7],
[0, 0, 0, 0]],
[[0, 3, 4, 5],
[0, 6, 7, 8],
[0, 0, 0, 0]]]
参数:
shape = [2, 2, -1]
offsets = [0, 0, 1]
输出:
Out.shape = [2, 2, 3]
Out.data = [[[1, 2, 3],
[5, 6, 7]],
[[3, 4, 5],
[6, 7, 8]]]示例二图解说明:
下图展示了示例二中的情形——一个形状为[2,3,4]的三维张量通过 crop 操作裁剪为形状为[2,2,3]的三维张量,同时保持了张量中元素的顺序和值不变。通过比较,可以清晰地看到张量形状变化前后各元素的对应关系。
.. figure:: ../../images/api_legend/crop.png
:width: 500
:alt: 示例二图示
:align: center参数
:::::::::
- x (Tensor) - 1-D 到 6-D Tensor,数据类型为 float32、float64、int32 或者 int64。
- shape (list|tuple|Tensor,可选) - 输出 Tensor 的形状,数据类型为 int32。如果是列表或元组,则其长度必须与 x 的维度大小相同,如果是 Tensor,则其应该是 1-D Tensor。当它是列表时,每一个元素可以是整数或者形状为[]的 0-D Tensor。含有 Tensor 的方式适用于每次迭代时需要改变输出形状的情况。
- offsets (list|tuple|Tensor,可选) - 每个维度上裁剪的偏移量,数据类型为 int32。如果是列表或元组,则其长度必须与 x 的维度大小相同,如果是 Tensor,则其应是 1-D Tensor。当它是列表时,每一个元素可以是整数或者形状为[]的 0-D Tensor。含有 Tensor 的方式适用于每次迭代的偏移量(offset)都可能改变的情况。默认值:None,每个维度的偏移量为 0。
- name (str,可选) - 具体用法请参见 :ref:
api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::
裁剪后的 Tensor,数据类型与输入(x)相同。
代码示例
:::::::::
COPY-FROM: paddle.crop
File: docs/api/paddle/cross_cn.rst
[Binary file]
File: docs/api/paddle/CUDAPinnedPlace_cn.rst
.. _cn_api_paddle_CUDAPinnedPlace:
CUDAPinnedPlace
.. py:class:: paddle.CUDAPinnedPlace
CUDAPinnedPlace 是一个设备描述符,它所指代的页锁定内存由 CUDA 函数 cudaHostAlloc() 在主机内存上分配,主机的操作系统将不会对这块内存进行分页和交换操作,可以通过直接内存访问技术访问,加速主机和 GPU 之间的数据拷贝。
有关 CUDA 的数据转移和 pinned memory,参见 官方文档 <https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/index.html#pinned-memory>_ 。
代码示例
::::::::::::
COPY-FROM: paddle.CUDAPinnedPlace
File: docs/api/paddle/CUDAPlace_cn.rst
.. _cn_api_paddle_CUDAPlace:
CUDAPlace
.. py:class:: paddle.CUDAPlace
CUDAPlace 是一个设备描述符,表示一个分配或将要分配 Tensor 的 GPU 设备。
每个 CUDAPlace 有一个 dev_id (设备 id)来表明当前的 CUDAPlace 所代表的显卡编号,编号从 0 开始。dev_id 不同的 CUDAPlace 所对应的内存不可相互访问。
这里编号指的是可见显卡的逻辑编号,而不是显卡实际的编号。
可以通过 CUDA_VISIBLE_DEVICES 环境变量限制程序能够使用的 GPU 设备,程序启动时会遍历当前的可见设备,并从 0 开始为这些设备编号。
如果没有设置 CUDA_VISIBLE_DEVICES,则默认所有的设备都是可见的,此时逻辑编号与实际编号是相同的。
参数
::::::::::::
- id (int) - GPU 的设备 ID。
代码示例
::::::::::::
COPY-FROM: paddle.CUDAPlace
File: docs/api/paddle/cummax_cn.rst
[Binary file]
File: docs/api/paddle/cummin_cn.rst
[Binary file]
File: docs/api/paddle/cumprod__cn.rst
.. cn_api_paddle_cumprod:
cumprod\_
.. py:function:: paddle.cumprod_(x, dim=None, dtype=None, name=None)
Inplace 版本的 :ref:cn_api_paddle_cumprod API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/cumprod_cn.rst
.. _cn_api_paddle_cumprod:
cumprod
.. py:function:: paddle.cumprod(x, dim=None, dtype=None, name=None)
沿给定维度 dim 计算输入 tensor x 的累乘。
.. note::
结果的第一个元素和输入的第一个元素相同。
参数
:::::::::
- x (Tensor) - 累乘的输入,需要进行累乘操作的 tensor。
- dim (int,可选) - 指明需要累乘的维度,取值范围需在[-x.rank,x.rank)之间,其中 x.rank 表示输入 tensor x 的维度,-1 代表最后一维。
- dtype (str|paddle.dtype|np.dtype,可选) - 输出 tensor 的数据类型,支持 int32、int64、bfloat16、float16、float32、float64、complex64、complex128。如果指定了,那么在执行操作之前,输入的 tensor 将被转换为 dtype 类型。这对于防止数据类型溢出非常有用。默认为:None。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::Tensor,累乘操作的结果。
代码示例
::::::::::
COPY-FROM: paddle.cumprod
File: docs/api/paddle/cumsum__cn.rst
.. cn_api_paddle_cumsum:
cumsum\_
.. py:function:: paddle.cumsum_(x, axis=None, dtype=None, name=None)
Inplace 版本的 :ref:cn_api_paddle_cumsum API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/cumsum_cn.rst
.. _cn_api_paddle_cumsum:
cumsum
.. py:function:: paddle.cumsum(x, axis=None, dtype=None, name=None, *, out=None)
沿给定 axis 计算 Tensor x 的累加和。
注意:结果的第一个元素和输入的第一个元素相同。
.. note::
别名支持: 参数名 input 可替代 x 和 dim 可替代 axis,如 input=tensor_x 等价于 x=tensor_x, dim=2 等价于 axis=2。
参数
:::::::::
- x (Tensor) - 累加的输入,需要进行累加操作的 Tensor。别名 input。
- axis (int,可选) - 指明需要累加的维度。-1 代表最后一维。默认:None,将输入展开为一维变量再进行累加计算。别名 dim。
- dtype (str|paddle.dtype|np.dtype,可选) - 输出 Tensor 的数据类型,支持 int32、int64、bfloat16、float16、float32、float64、complex64、complex128。当输入 x 的类型是 int8/int16/int32 时,默认值是 int64;否则默认值是 None。如果不为 None,那么在执行操作之前,输入 Tensor 将被转换为 dtype。这对于防止数据类型溢出非常有用。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
关键字参数
:::::::::
- **out** (Tensor,可选) - 输出 Tensor,若不为 ``None``,计算结果将保存在该 Tensor 中,默认值为 ``None``。返回
:::::::::Tensor,累加的结果。
代码示例
::::::::::
COPY-FROM: paddle.cumsum
File: docs/api/paddle/cumulative_trapezoid_cn.rst
.. _cn_api_paddle_cumulative_trapezoid:
cumulative_trapezoid
.. py:function:: paddle.cumulative_trapezoid(y, x=None, dx=None, axis=-1, name=None, *, out=None)
在指定维度上对输入实现 trapezoid rule <https://en.wikipedia.org/wiki/Trapezoidal_rule>_ 算法。与 :ref:cn_api_paddle_trapezoid 的区别是,所用累积求和函数为 cumsum。
参数
:::::::::
- **y** (Tensor) - 输入多维 Tensor,可选的数据类型为 float16、float32、float64。
- **x** (Tensor,可选) - ``y`` 中数值对应的浮点数所组成的 Tensor,类型与 ``y`` 相同,形状与 ``y`` 的形状相匹配;若 ``x`` 有输入,已知 ``y`` 的尺寸为 ``[d_1, d_2, ... , d_n]`` 且 ``axis=k``,则 ``x`` 的尺寸只能为 ``[d_k]`` 或 ``[d_1, d_2, ... , d_n]``;如果 ``x`` 为 None,则假定采样点均匀分布 ``dx``。
- **dx** (float,可选) - 相邻采样点之间的常数间隔;当 ``x`` 和 ``dx`` 均未指定时,``dx`` 默认为 1.0。
- **axis** (int,可选) - 计算 trapezoid rule 时 ``y`` 的维度。默认值 -1。别名 ``dim``。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。关键字参数
:::::::::
- **out** (Tensor,可选) - 输出 Tensor,若不为 ``None``,计算结果将保存在该 Tensor 中,默认值为 ``None``。返回
:::::::::
Tensor,按 trapezoidal rule 计算出 y 等于 N 维张量时的定积分,结果为 N 维张量。
代码示例
:::::::::
COPY-FROM: paddle.cumulative_trapezoid
File: docs/api/paddle/DataParallel_cn.rst
[Binary file]
File: docs/api/paddle/deg2rad_cn.rst
.. _cn_api_paddle_deg2rad:
deg2rad
.. py:function:: paddle.deg2rad(x, name=None, *, out=None)
将元素从度转换为弧度
.. math::
deg2rad(x)=\pi * x / 180参数
:::::::::
- **x** (Tensor) - 输入的 Tensor,数据类型为:int32、int64、float32、float64。
- **name** (str,可选) - 操作的名称(可选,默认值为 None)。更多信息请参见 :ref:`api_guide_Name`。关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
:::::::::
输出 Tensor,与 x 维度相同、数据类型相同(输入为 int 时,输出数据类型为 float32)。
代码示例
:::::::::
COPY-FROM: paddle.deg2rad
File: docs/api/paddle/diag_cn.rst
[Binary file]
File: docs/api/paddle/diag_embed_cn.rst
[Binary file]
File: docs/api/paddle/diagflat_cn.rst
[Binary file]
File: docs/api/paddle/diagonal_cn.rst
[Binary file]
File: docs/api/paddle/diagonal_scatter_cn.rst
[Binary file]
File: docs/api/paddle/diff_cn.rst
.. _cn_api_paddle_diff:
diff
.. py:function:: paddle.diff(x, n=1, axis=-1, prepend=None, append=None, name=None, *, out=None)
沿着指定轴计算输入 Tensor 的 n 阶前向差值,一阶的前向差值计算公式如下:
.. math::
out[i] = x[i+1] - x[i]
.. note::
高阶的前向差值可以通过递归的方式进行计算,n 的值支持任意正整数。
.. note::
别名支持: 参数名 input 可替代 x 和 dim 可替代 axis,如 input=tensor_x 等价于 x=tensor_x, dim=1 等价于 axis=1。
参数
::::::::::::
- **x** (Tensor) - 待计算前向差值的输入 ``Tensor``,支持 bool、int32、int64、float16、float32、float64 数据类型。别名 ``input``。
- **n** (int,可选) - 需要计算前向差值的次数,``n`` 的值支持任意正整数,默认值为 1。
- **axis** (int,可选) - 沿着哪一维度计算前向差值,默认值为-1,也即最后一个维度。别名 ``dim``。
- **prepend** (Tensor,可选) - 在计算前向差值之前,沿着指定维度 axis 附加到输入 x 的前面,它的维度需要和输入一致,并且除了 axis 维外,其他维度的形状也要和输入一致,默认值为 None。
- **append** (Tensor,可选) - 在计算前向差值之前,沿着指定维度 axis 附加到输入 x 的后面,它的维度需要和输入一致,并且除了 axis 维外,其他维度的形状也要和输入一致,默认值为 None。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。关键字参数
:::::::::
- **out** (Tensor,可选) - 输出 Tensor,若不为 ``None``,计算结果将保存在该 Tensor 中,默认值为 ``None``。返回
:::::::::
前向差值计算后的 Tensor,数据类型和输入一致。
代码示例
:::::::::
COPY-FROM: paddle.diff
File: docs/api/paddle/digamma__cn.rst
.. cn_api_paddle_digamma:
digamma\_
.. py:function:: paddle.digamma_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_digamma API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/digamma_cn.rst
.. _cn_api_paddle_digamma:
digamma
.. py:function:: paddle.digamma(x, name=None)
逐元素计算输入 Tensor 的 digamma 函数值
.. math::
\Out = \Psi(x) = \frac{ \Gamma^{'}(x) }{ \Gamma(x) }\
参数
:::::::::
- x (Tensor) – 输入 Tensor。数据类型为 float32,float64。
- name (str,可选) - 具体用法请参见 :ref:
api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::Tensor, digamma 函数计算结果,数据类型和维度大小与输入一致。
代码示例
:::::::::
COPY-FROM: paddle.digamma
File: docs/api/paddle/disable_compat_cn.rst
.. _cn_api_paddle_disable_compat:
disable_compat
.. py:function:: paddle.disable_compat()
通过从 sys.meta_path 中移除 TorchProxyMetaFinder 来禁用 PyTorch 代理。
这可以防止 torch 导入被代理到 PaddlePaddle。
返回
:::::::::
None
代码示例
:::::::::
COPY-FROM: paddle.disable_compat
File: docs/api/paddle/disable_signal_handler_cn.rst
.. _cn_api_paddle_disable_signal_handler:
disable_signal_handler
.. py:function:: paddle.disable_signal_handler()
关闭 Paddle 系统信号处理方法
Paddle 默认在 C++层面注册了系统信号处理方法,用于优化报错信息。
但是一些特定的 Python module 可能需要使用某些系统信号,引发冲突。
您可以通过调用本函数来关闭 Paddle 的系统信号处理方法
如果您在一个 Python 文件中同时使用了 Paddle 和下述框架的一种或多种,
则请在其他框架执行前首先调用 paddle.disable_signal_handler()
1.TVM 框架
2.ADLIK 框架
返回
:::::::::
无
代码示例
:::::::::
COPY-FROM: paddle.disable_signal_handler
File: docs/api/paddle/disable_static_cn.rst
.. _cn_api_paddle_disable_static:
disable_static
.. py:function:: paddle.disable_static(place=None)
.. note::
从 2.0.0 版本开始,Paddle 默认开启动态图模式。
该接口关闭静态图模式。可通过 :ref:cn_api_paddle_enable_static 开启静态图模式。
参数
::::::::::::
- place (paddle.CPUPlace|paddle.CUDAPlace,可选) - 动态图运行时的设备。默认值为
None,此时,会根据 paddle 的版本自动判断。
返回
::::::::::::
无
代码示例
::::::::::::
COPY-FROM: paddle.disable_static
File: docs/api/paddle/dist_cn.rst
.. _cn_api_paddle_dist:
dist
.. py:function:: paddle.dist(x, y, p=2, name=None)
计算 :math:(x-y) 的 :math:p 范数(p-norm),需要注意这不是严格意义上的范数,仅作为距离的度量。输入 :math:x 和 :math:y 的形状(shape)必须是可广播的(broadcastable)。其含义如下,详情请参考 Tensor 的广播机制 <../../guides/beginner/tensor_cn.html#id7>_ :
- 每个输入都至少有 1 维
- 对两个输入的维度从后向前匹配,两个输入每一维的大小需要满足 3 个条件中的任意一个:相等、其中一个为 1 或者其中一个不存在。
定义 :math:z=x-y,:math:x 和 :math:y 的形状是可广播的,那么 :math:z 的形状可按照下列步骤得到:
(1) 如果 :math:x 和 :math:y 的维数不同,先对维数较少的这个输入的维度往前补 1。
例如,:math:x 的形状为 [8, 1, 6, 1],:math:y 的形状为 [7, 1, 5],对 :math:y 的维度补 1,
x (4-D Tensor): 8 x 1 x 6 x 1
y (4-D Tensor): 1 x 7 x 1 x 5
(2) 确定输出 :math:z 每一维度的大小:从两个输入的维度中选取最大值。
z (4-D Tensor): 8 x 7 x 6 x 5
若两个输入的维数相同,则输出的大小可直接用步骤 2 确定。以下是 :math:p 取不同值时,范数的计算公式:
当 :math:p = 0,定义 :math:0^0 = 0,则 :math:z 的零范数是 :math:z 中非零元素的个数。
.. math::
||z||{0}=\lim{p \rightarrow 0}\sum_{i=1}^{m}|z_i|^{p}
当 :math:p = \infty 时,:math:z 的无穷范数是 :math:z 所有元素中的绝对值最大值。
.. math::
||z||_\infty=\max_i |z_i|
当 :math:p = -\infty 时,:math:z 的负无穷范数是 :math:z 所有元素中的绝对值最小值。
.. math::
||z||_{-\infty}=\min_i |z_i|
其他情况下,:math:z 的 :math:p 范数使用以下公式计算:
.. math::
||z||{p}=(\sum{i=1}^{m}|z_i|^p)^{\frac{1}{p}}
参数
::::::::::::
- x (Tensor) - 1-D 到 6-D Tensor,数据类型为 bfloat16,float16,float32 或 float64。别名
input。 - y (Tensor) - 1-D 到 6-D Tensor,数据类型为 bfloat16,float16,float32 或 float64。别名
other。 - p (float,可选) - 用于设置需要计算的范数,数据类型为 float32 或 float64。默认值为 2。
- name (str,可选) - 具体用法请参见 :ref:
api_guide_Name,一般无需设置,默认值为 None。
返回
::::::::::::
Tensor,:math:(x-y) 的 :math:p 范数。
代码示例
::::::::::::
COPY-FROM: paddle.dist
File: docs/api/paddle/div__cn.rst
.. cn_api_paddle_div:
div\_
.. py:function:: paddle.div_(x, y, name=None, *, rounding_mode=None, out=None)
别名函数,功能与 :ref:cn_api_paddle_divide_ 完全相同,详情请参考 :ref:cn_api_paddle_divide_ 。
File: docs/api/paddle/div_cn.rst
.. _cn_api_paddle_div:
div
.. py:function:: paddle.div(x, y, name=None, *, rounding_mode=None, out=None)
别名函数,功能与 :ref:cn_api_paddle_divide 完全相同,详情请参考 :ref:cn_api_paddle_divide 。
File: docs/api/paddle/divide__cn.rst
.. cn_api_paddle_divide:
divide\_
.. py:function:: paddle.divide_(x, y, name=None, *, rounding_mode=None, out=None)
Inplace 版本的 :ref:cn_api_paddle_divide API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/divide_cn.rst
.. _cn_api_paddle_divide:
divide
.. py:function:: paddle.divide(x, y, name=None, *, rounding_mode=None, out=None)
逐元素相除算子,输入 x 与输入 y 逐元素相除,并将各个位置的输出元素保存到返回结果中。
.. note::
别名支持:参数名 input 可替代 x,参数名 other 可替代 y ,如 divide(input=tensor_x, other=tensor_y, ...) 等价于 divide(x=tensor_x, y=tensor_y, ...) 。
输入 x 与输入 y 必须和广播为相同形状,关于广播规则,请参见 Tensor 介绍_ 。
.. _Tensor 介绍: ../../guides/beginner/tensor_cn.html#id7等式为:
.. math::
Out = X / Y
- :math:
X:多维 Tensor。 - :math:
Y:多维 Tensor。
参数
:::::::::
- x (Tensor) - 多维 Tensor。数据类型为 bool、bfloat16、float16、float32、float64、int8、int16、int32、int64、uint8、complex64、complex128。
别名: input
- y (Tensor) - 多维 Tensor。数据类型为 bool、bfloat16、float16、float32、float64、int8、int16、int32、int64、uint8、complex64、complex128。
别名: other
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
- rounding_mode (str,可选) - 指定舍入模式。可选值为 None、"trunc" 或 "floor"。如果 rounding_mode=None,则不进行舍入操作;如果 rounding_mode="trunc",则向零截断;如果 rounding_mode="floor",则向负无穷舍入。
- out (Tensor,可选) - 输出 Tensor,默认值为 None。
返回
:::::::::
Tensor,存储运算后的结果。如果 x 和 y 有不同的 shape 且是可以广播的,返回 Tensor 的 shape 是 x 和 y 经过广播后的 shape。如果 x 和 y 有相同的 shape,返回 Tensor 的 shape 与 x,y 相同。
代码示例
:::::::::
COPY-FROM: paddle.divide
File: docs/api/paddle/dot_cn.rst
[Binary file]
File: docs/api/paddle/dsplit_cn.rst
.. _cn_api_paddle_dsplit:
dsplit
.. py:function:: paddle.dsplit(x, num_or_indices, name=None)
dsplit 全称 Depth Split ,即深度分割,将输入 Tensor 沿着深度轴分割成多个子 Tensor,等价于将 :ref:cn_api_paddle_tensor_split API 的参数 axis 固定为 2。
.. note::
请确保使用 paddle.dsplit 进行变换的 Tensor 维度数量不少于 3。
如下图,Tensor x 的 shape 为[4, 4, 4],经过 paddle.dsplit(x, num_or_indices=2) 变换后,得到 out0 和 out1 两个 shape 均为[4, 4, 2]的子 Tensor:
.. image:: ../../images/api_legend/dsplit/dsplit.png
:alt: dsplit 图例
参数
:::::::::
- x (Tensor) - 输入变量,数据类型为 bool、bfloat16、float16、float32、float64、uint8、int8、int32、int64 的多维 Tensor,其维度必须大于 2。
- num_or_indices (int|list|tuple) - 如果 num_or_indices 是一个整数 n ,则 x 拆分为 n 部分。如果 num_or_indices 是整数索引的列表或元组,则在每个索引处分割 x 。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::
list[Tensor],分割后的 Tensor 列表。
代码示例
:::::::::
COPY-FROM: paddle.dsplit
File: docs/api/paddle/dstack_cn.rst
.. _cn_api_paddle_dstack:
dstack
.. py:function:: paddle.dstack(x, name=None)
沿深度轴堆叠输入 x 中的所有张量。所有张量必须具有相同的数据类型。
参数
::::::::::::
- **x** (list[Tensor]|tuple[Tensor]) - 输入 ``x`` 可以是张量的 list 或 tuple, ``x`` 中张量的数据类型必须相同。支持的数据类型: ``float16`` 、 ``float32`` 、 ``float64`` 、 ``int32`` 、 ``int64`` 或 ``bfloat16`` 。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
Tensor,与输入数据类型相同的堆叠张量。
也可以参考下方的图示来理解 dstack 是如何对张量进行变换的。图片展示了两个形状为 [3] 的一维张量以及两个形状为 [3, 2] 的二维张量,这些张量在深度方向上堆叠后的结果。其中,形状为 [3] 的一维张量在堆叠时会被扩展为形状为 [1, 3] 的二维张量。
.. image:: ../../images/api_legend/dstack.png
:width: 500
:alt: 图例
代码示例
::::::::::::
COPY-FROM: paddle.dstack
File: docs/api/paddle/einsum_cn.rst
.. _cn_api_paddle_einsum:
einsum
.. py:function:: paddle.einsum(equation, *operands)
该函数用于对一组输入 Tensor 进行 Einstein 求和,该函数目前仅适用于动态图。
Einstein 求和是一种采用 Einstein 标记法描述的 Tensor 求和,输入单个或多个 Tensor,输出单个 Tensor。
如下的 Tensor 操作或运算均可视为 Einstein 求和的特例
- 单操作数
- 迹:trace
- 对角元:diagonal
- 转置:transpose
- 求和:sum
- 双操作数
- 内积:dot
- 外积:outer
- 广播乘积:mul,*
- 矩阵乘:matmul
- 批量矩阵乘:bmm
- 多操作数
- 广播乘积:mul,*
- 多矩阵乘:A.matmul(B).matmul(C)关于求和标记的约定
- 维度分量下标:Tensor 的维度分量下标使用英文字母表示,不区分大小写,如'ijk'表示 Tensor 维度分量为 i,j,k
- 下标对应输入操作数:维度下标以 ``,`` 分段,按顺序 1-1 对应输入操作数
- 广播维度:省略号 ``...`` 表示维度的广播分量,例如,'i...j'表示首末分量除外的维度需进行广播对齐
- 自由标和哑标:输入标记中仅出现一次的下标为自由标,重复出现的下标为哑标,哑标对应的维度分量将被规约消去
- 输出:输出 Tensor 的维度分量既可由输入标记自动推导,也可以用输出标记定制化
- 自动推导输出
- 广播维度分量位于维度向量高维位置,自由标维度分量按字母顺序排序,位于维度向量低纬位置,哑标维度分量不输出
- 定制化输出
- 维度标记中 ``->`` 右侧为输出标记
- 若输出包含广播维度,则输出标记需包含 ``...``
- 输出标记为空时,对输出进行全量求和,返回该标量
- 输出不能包含输入标记中未出现的下标
- 输出下标不可以重复出现
- 哑标出现在输出标记中则自动提升为自由标
- 输出标记中未出现的自由标被降为哑标
- 例子
- '...ij, ...jk',该标记中 i,k 为自由标,j 为哑标,输出维度'...ik'
- 'ij -> i',i 为自由标,j 为哑标
- '...ij, ...jk -> ...ijk',i,j,k 均为自由标
- '...ij, ...jk -> ij',若输入 Tensor 中的广播维度不为空,则该标记为无效标记求和规则
Einsum 求和过程理论上等价于如下四步,但实现中实际执行的步骤会有差异。
- 第一步,维度对齐:将所有标记按字母序排序,按照标记顺序将输入 Tensor 逐一转置、补齐维度,使得处理后的所有 Tensor 其维度标记保持一致
- 第二步,广播乘积:以维度下标为索引进行广播点乘
- 第三步,维度规约:将哑标对应的维度分量求和消除
- 第四步,转置输出:若存在输出标记,则按标记进行转置,否则按广播维度+字母序自由标的顺序转置,返回转之后的 Tensor 作为输出关于 trace 和 diagonal 的标记约定(待实现功能)
- 在单个输入 Tensor 的标记中重复出现的下标称为对角标,对角标对应的坐标轴需进行对角化操作,如'i...i'表示需对首尾坐标轴进行对角化
- 若无输出标记或输出标记中不包含对角标,则对角标对应维度规约为标量,相应维度取消,等价于 trace 操作
- 若输出标记中包含对角标,则保留对角标维度,等价于 diagonal 操作参数
:::::
- **equation** (str):求和标记
- **operands** (Tensor, [Tensor, ...]):输入 Tensor返回
:::::
Tensor:输出 Tensor代码示例
:::::::::
COPY-FROM: paddle.einsum
File: docs/api/paddle/empty_cn.rst
.. _cn_api_paddle_empty:
empty
.. py:function:: paddle.empty(shape, dtype=None, name=None, *, out=None, device=None, requires_grad=False, pin_memory=False)
创建形状大小为 shape 并且数据类型为 dtype 的 Tensor,其中元素值是未初始化的。
.. note::
别名支持: 参数名 size 可替代 shape。
shape 支持可变参数类型。
使用实例:
paddle.empty(1, 2, 3, dtype=paddle.float32)
paddle.empty(size=[1, 2, 3], dtype=paddle.float32)
参数
::::::::::::
- **shape** (list|tuple|Tensor|*shape) - 生成的 Tensor 的形状。数据类型为 int32 或 int64。
如果 ``shape`` 是 list、tuple,则其中的元素可以是 int,或者是形状为 [] 且数据类型为 int32、int64 的 0-D Tensor。
如果 ``shape`` 是 Tensor,则是数据类型为 int32、int64 的 1-D Tensor,表示一个列表。
如果 ``shape`` 是 \*shape,则可以直接以可变参数的形式传入多个整数(例如 ``randn(2, 3)``)。
该参数的别名为 ``size``。
- **dtype** (str|paddle.dtype|np.dtype,可选)- 输出变量的数据类型,可以是 bool、float16、float32、float64、int32、int64、complex64、complex128。若为 None,则输出变量的数据类型为系统全局默认类型,默认值为 None。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。关键字参数
::::::::::::
- out (Tensor,可选) - 用于存储结果的 Tensor。若指定,将直接写入该 Tensor,默认值为 None。
- device (PlaceLike|None,可选) - 期望创建 Tensor 所在的设备。默认值为 None,表示使用当前全局设备(可通过 paddle.device.set_device 设置)。
- requires_grad (bool,可选) - 是否需要为返回的 Tensor 记录梯度信息。默认值为 False。
- pin_memory (bool,可选) - 若为 True,返回的 Tensor 将分配在锁页内存中。默认值为 False。
返回
::::::::::::
返回一个根据 shape 和 dtype 创建并且尚未初始化的 Tensor。
代码示例
::::::::::::
COPY-FROM: paddle.empty
File: docs/api/paddle/empty_like_cn.rst
.. _cn_api_paddle_empty_like:
empty_like
.. py:function:: paddle.empty_like(x, dtype=None, name=None, *, device=None, requires_grad=False, pin_memory=False)
根据参数 x 的 shape 和数据类型 dtype 创建未初始化的 Tensor。如果 dtype 为 None,则 Tensor 的数据类型与 x 相同。
.. note::
别名支持: 参数名 input 可替代 x,如 empty_like(input=tensor_x) 等价于 empty_like(x=tensor_x) 。
参数
::::::::::::
- **x** (Tensor) – 输入 Tensor,输出 Tensor 和 x 具有相同的形状,x 的数据类型可以是 bool、float16、float32、float64、int32、int64。别名: ``input``。
- **dtype** (str|paddle.dtype|np.dtype,可选)- 输出变量的数据类型,可以是 bool、float16、float32、float64、int32、int64。若参数为 None,则输出变量的数据类型和输入变量相同,默认值为 None。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。关键字参数
::::::::::::
- device (PlaceLike|None,可选) - 期望创建 Tensor 所在的设备。若为 None,则与 x 保持一致。
- requires_grad (bool,可选) - 是否需要为返回的 Tensor 记录梯度信息。默认值为 False。
- pin_memory (bool,可选) - 若为 True,返回的 Tensor 将分配在锁页内存中。默认值为 False。
返回
::::::::::::
返回一个根据 x 和 dtype 创建并且尚未初始化的 Tensor。
代码示例
::::::::::::
COPY-FROM: paddle.empty_like
File: docs/api/paddle/enable_compat_cn.rst
.. _cn_api_paddle_enable_compat:
enable_compat
.. py:function:: paddle.enable_compat(*, scope=None, blocked_modules=None, backend='torch', silent=False)
通过将 TorchProxyMetaFinder 添加到 sys.meta_path 来启用 PyTorch 兼容代理。
这允许导入实际上是 PaddlePaddle 代理的 torch 模块。
参数
:::::::::
- scope (str|Iterable[str],可选) - 指定启用 PyTorch 兼容代理的模块或模块列表。如果为 None,则全局启用 PyTorch 兼容代理。默认为 None。
- blocked_modules (str|Iterable[str],可选) - 指定从 PyTorch 兼容代理中排除的模块或模块列表。默认为 None。
- backend (str,可选) - 要启用兼容性的后端。目前仅支持 "torch"。默认为 "torch"。
- silent (bool,可选) - 如果为 True,则抑制有关范围更改的警告。默认为 False。
返回
:::::::::
None
代码示例 1
:::::::::
COPY-FROM: paddle.enable_compat:enable-compat-in-global-scope
代码示例 2
:::::::::
COPY-FROM: paddle.enable_compat:enable-compat-in-specific-scope
File: docs/api/paddle/enable_grad_cn.rst
.. _cn_api_paddle_enable_grad:
enable_grad
.. py:class:: paddle.enable_grad()
创建一个上下文来启用动态图梯度计算。在此模式下,每次计算的结果都将具有 stop_gradient=False。
也可以用作一个装饰器(需要创建实例对象作为装饰器)。
代码示例
::::::::::::
COPY-FROM: paddle.enable_grad
File: docs/api/paddle/enable_static_cn.rst
.. _cn_api_paddle_enable_static:
enable_static
.. py:function:: paddle.enable_static()
.. note::
从 2.0.0 版本开始,Paddle 默认开启动态图模式。
开启静态图模式。可通过 :ref:cn_api_paddle_disable_static 关闭静态图模式。
返回
::::::::::::
无
代码示例
::::::::::::
COPY-FROM: paddle.enable_static
File: docs/api/paddle/eq_cn.rst
.. _cn_api_paddle_eq:
eq
.. py:function:: paddle.eq(x, y, name=None, *, out=None)
equal 的别名,请参考 :ref:cn_api_paddle_equal。
File: docs/api/paddle/equal__cn.rst
.. cn_api_paddle_equal:
equal\_
.. py:function:: paddle.equal_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_equal API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/equal_all_cn.rst
.. _cn_api_paddle_equal_all:
equal_all
.. py:function:: paddle.equal_all(x, y, name=None)
返回 x==y 的布尔值,如果所有相同位置的元素相同返回 True,否则返回 False。
注:输出的结果不返回梯度。
参数
::::::::::::
- **x** (Tensor) - 输入 Tensor,支持的数据类型包括 bool、float32、float64、int32、int64。
- **y** (Tensor) - 输入 Tensor,支持的数据类型包括 bool、float32、float64、int32、int64。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
输出结果为 Tensor,Tensor 数据类型为 bool。
代码示例
::::::::::::
COPY-FROM: paddle.equal_all
File: docs/api/paddle/equal_cn.rst
.. _cn_api_paddle_equal:
equal
.. py:function:: paddle.equal(x, y, name=None)
返回 :math:x==y 逐元素比较 x 和 y 是否相等,相同位置的元素相同则返回 True,否则返回 False。使用重载算子 == 可以有相同的计算函数效果。
.. note::
输出的结果不返回梯度。
参数
::::::::::::
- **x** (Tensor) - 输入 Tensor,支持的数据类型包括 bool、float16、float32、float64、uint8、int8、int16、int32、int64。
- **y** (Tensor) - 输入 Tensor,支持的数据类型包括 bool、float16、float32、float64、uint8、int8、int16、int32、int64。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
输出结果的 Tensor,输出 Tensor 的 shape 和输入一致,Tensor 数据类型为 bool。
代码示例
::::::::::::
COPY-FROM: paddle.equal
File: docs/api/paddle/erf__cn.rst
.. cn_api_paddle_erf:
erf\_
.. py:function:: paddle.erf_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_erf API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
.. note::
别名支持:参数名 ``input`` 可替代 ``x``,如 ``erf_(input=tensor_x)`` 等价于 ``erf_(x=tensor_x)``。File: docs/api/paddle/erf_cn.rst
.. _cn_api_paddle_erf:
erf
.. py:function:: paddle.erf(x, name=None)
逐元素计算 Erf 激活函数。
更多细节请参考 Error function <https://en.wikipedia.org/wiki/Error_function>_。
.. math::
out = \frac{2}{\sqrt{\pi}} \int_{0}^{x}e^{- \eta^{2}}d\eta
参数
::::::::::::
- **x** (Tensor) - 输入 Tensor,数据类型为 float32、float64、uint8、int8、int16、int32、int64。别名: ``input``。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 ``None``。返回
::::::::::::
Tensor,数据类型为 float32 或 float64(整数类型会自动转换为 float32),形状与输入 ``x`` 相同。代码示例
::::::::::::
COPY-FROM: paddle.erf
File: docs/api/paddle/erfinv__cn.rst
.. cn_api_paddle_erfinv:
erfinv\_
.. py:function:: paddle.erfinv_(x)
Inplace 版本的 :ref:cn_api_paddle_erfinv API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/erfinv_cn.rst
.. _cn_api_paddle_erfinv:
erfinv
.. py:function:: paddle.erfinv(x, name=None)
计算输入矩阵 x 的逆误差函数。
请参考 erf 计算公式 :ref:cn_api_paddle_erf
.. math::
erfinv(erf(x)) = x
参数
:::::::::
- **x** (Tensor) - 输入的 Tensor,数据类型为:float16、bfloat16、float32、float64。
- **name** (str,可选) - 操作的名称(可选,默认值为 None)。更多信息请参见 :ref:`api_guide_Name`。返回
:::::::::
输出 Tensor,与 :attr:x 数据类型相同。
代码示例
:::::::::
COPY-FROM: paddle.erfinv
File: docs/api/paddle/exp__cn.rst
.. cn_api_paddle_exp:
exp\_
.. py:function:: paddle.exp_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_exp API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/exp_cn.rst
.. _cn_api_paddle_exp:
exp
.. py:function:: paddle.exp(x, name=None)
对输入,逐元素进行以自然数 e 为底指数运算。
.. math::
out = e^x
参数
::::::::::::
- **x** (Tensor) - 该 OP 的输入为多维 Tensor。数据类型为 int32、int64、bfloat16、float16、float32、float64、complex64、complex128。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
输出为 Tensor,与 x 维度相同、数据类型相同。
代码示例
::::::::::::
COPY-FROM: paddle.exp
File: docs/api/paddle/expand_as_cn.rst
.. _cn_api_paddle_expand_as:
expand_as
.. py:function:: paddle.expand_as(x, y, name=None)
根据 y 的形状扩展 x,扩展后,x 的形状和 y 的形状相同。
x 的维数和 y 的维数应小于等于 6,并且 y 的维数应该大于等于 x 的维数。扩展的维度的维度值应该为 1。
下图展示了一个一维张量通过 expand_as 操作转变为形状为[2,3]的张量。目标张量的形状为[2,3],通过 expand_as,一维张量扩展成形状为[2,3]的张量。
.. image:: ../../images/api_legend/expand_as.png
:width: 500
:alt: 图例
.. note::
别名支持: 参数名 input 可替代 x, other 可替代 y。
参数
:::::::::
- x (Tensor) - 输入的 Tensor,数据类型为:bool、float32、float64、int32 或 int64。
别名: input
- y (Tensor) - 给定输入 x 扩展后的形状。
别名: other
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::
Tensor,数据类型与 x 相同。
代码示例
:::::::::
COPY-FROM: paddle.expand_as
File: docs/api/paddle/expand_cn.rst
.. _cn_api_paddle_expand:
expand
.. py:function:: paddle.expand(x, shape, name=None)
根据 shape 指定的形状扩展 x,扩展后,x 的形状和 shape 指定的形状一致。
x 的维数和 shape 的元素数应小于等于 6,并且 shape 中的元素数应该大于等于 x 的维数。扩展的维度的维度值应该为 1。
示例图解说明:
Original Tensor 显示了一个形状为 [3] 的一维张量 [1, 2, 3]。通过 paddle.expand 方法(参数 shape = [2, 3])被广播扩展为一个形状为 [2, 3] 的二维张量。
.. figure:: ../../images/api_legend/expand.png
:width: 500
:alt: 示例一图示
:align: center.. note::
别名支持: 别名支持: 参数名 input 可替代 x 和 size 可替代 shape。
shape 支持可变参数类型。
使用实例:
paddle.expand(tensor_x, shape=[3, 4], name=None)
tensor_x.expand([3, 4]) -> paddle.expand(tensor_x, [3, 4])
tensor_x.expand(3, 4) -> paddle.expand(tensor_x, 3, 4)
tensor_x.expand(size=[3, 4]) -> paddle.expand(tensor_x, size=[3, 4])
参数
:::::::::
- x (Tensor) - 输入的 Tensor,数据类型为:bool、float16、float32、float64、int32、int64、uint8 或 uint16。
别名: input
- shape (tuple|list|Tensor) - 给定输入 x 扩展后的形状,若 shape 为 list 或者 tuple,则其中的元素值应该为整数或者是形状为 1-D 或 0-D 的 Tensor,若 shape 类型为 Tensor,则其应该为 1-D Tensor。值为-1 表示保持相应维度的形状不变。支持可变参数类型。
别名: size
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::N-D Tensor,数据类型与 x 相同。
代码示例
:::::::::
COPY-FROM: paddle.expand
File: docs/api/paddle/expand_copy_cn.rst
.. _cn_api_paddle_expand_copy:
expand_copy
.. py:function:: paddle.expand_copy(x, shape, name=None)
根据 shape 指定的形状扩展 x,扩展后返回一个新的 Tensor,不会修改原 Tensor。
这是 :ref:cn_api_paddle_expand 的非原位版本,始终返回新的 Tensor 而非视图。
.. note::
该接口有两个签名:
1. paddle.expand_copy(x, shape, name=None) (Paddle 风格):根据广播语义返回扩展后的新 Tensor。
2. paddle.expand_copy(input, *size) (PyTorch 风格):通过可变长 size 参数返回扩展后的新 Tensor。
参数
:::::::::::
- x (Tensor) - 输入的 Tensor。别名 input。
- shape (tuple|list|Tensor) - 目标扩展形状。维度数必须大于或等于 x 的维度数。若 shape 为 list 或 tuple,其中的元素值应全为整数或 0-D 或 1-D Tensor(数据类型为 int32)。别名 size。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::::
Tensor,数据类型与 x 相同。
代码示例
:::::::::::
COPY-FROM: paddle.expand_copy
File: docs/api/paddle/expm1__cn.rst
.. cn_api_paddle_expm1:
expm1\_
.. py:function:: paddle.expm1_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_expm1 API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
.. note::
别名支持:参数名 ``input`` 可替代 ``x``,如 ``expm1_(input=tensor_x)`` 等价于 ``expm1_(x=tensor_x)``。File: docs/api/paddle/expm1_cn.rst
.. _cn_api_paddle_expm1:
expm1
.. py:function:: paddle.expm1(x, name=None)
对输入,逐元素进行以自然数 e 为底指数运算并减 1。
.. math::
out = e^x - 1
参数
:::::::::
- **x** (Tensor) - 该 OP 的输入为多维 Tensor。数据类型为:int32、int64、bfloat16、float16、float32、float64、complex64、complex128。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
:::::::::
输出为 Tensor,与 x 维度相同、数据类型相同。
代码示例
:::::::::
COPY-FROM: paddle.expm1
File: docs/api/paddle/eye_cn.rst
[Binary file]
File: docs/api/paddle/finfo_cn.rst
.. _cn_api_paddle_finfo:
finfo
.. py:function:: paddle.finfo(dtype)
返回一个 finfo 对象,该对象包含了输入 dtype 的各种相关的数值信息。其中输入 dtype 只能是整数类型的 paddle.dtype 。
其功能类似 numpy.finfo <https://numpy.org/doc/stable/reference/generated/numpy.finfo.html#numpy-finfo>_ 。
.. note::
别名支持: 参数名 type 可替代 dtype,如 type=paddle.float32 等价于 dtype=paddle.float32。
参数
:::::::::
- dtype (str|paddle.dtype|np.dtype,可选) - 输入的数据类型,可以是:paddle.float16、 paddle.float32、 paddle.float64、 paddle.bfloat16、 paddle.complex64、 paddle.complex128 或这些类型的字符串形式。别名: type。
返回
:::::::::
一个 finfo 对象,其中包含 8 个属性,如下所示:
- **min** (double) - 该数据类型所能表示的最小的数。
- **max** (double) - 该数据类型所能表示的最大的数。
- **eps** (double) - 该数据类型所能表示的最小数,使得 1.0 + eps ≠ 1.0 。
- **resolution** (double) - 这种类型的近似小数分辨率。
- **smallest_normal** (double) - 这种类型的最小的正 normal 数。
- **tiny** (double) - 这种类型的最小的正 normal 数,和 smallest_normal 相同。
- **bits** (int) - 该数据类型所占据的 bit 位数。
- **dtype** (str) - 该数据类型的字符串名称。代码示例
:::::::::
COPY-FROM: paddle.finfo
File: docs/api/paddle/fix_cn.rst
.. _cn_api_paddle_fix:
fix
.. py:function:: paddle.fix(input, name=None, *, out=None)
返回输入 Tensor 的截断整数值。与 paddle.trunc 功能相同。
参数
:::::::::
- input (Tensor) - 输入 Tensor,数据类型为 int32、int64、float32、float64。别名 x。
- name (str,可选) - 操作名称,默认值为 None。
关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
:::::::::
Tensor:截断后的 Tensor。
代码示例
:::::::::
COPY-FROM: paddle.fix
File: docs/api/paddle/flatten__cn.rst
.. cn_api_paddle_flatten:
flatten\_
.. py:function:: paddle.flatten_(x)
Inplace 版本的 :ref:cn_api_paddle_flatten API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/flatten_cn.rst
[Binary file]
File: docs/api/paddle/flip_cn.rst
.. _cn_api_paddle_flip:
flip
.. py:function:: paddle.flip(x, axis, name=None)
沿指定轴反转 n 维 Tensor。
下图展示了 flip 在 2 维和 3 维张量上的情形——一个形状为[4,4]的二维张量以及一个形状为[3,2,2]的三维张量在指定轴上进行翻转。通过比较,可以清晰地看到张量在翻转前后的变化。图例中展示了沿不同轴进行翻转的结果。
.. image:: ../../images/api_legend/flip.png
:width: 600
:alt: 图例
参数
::::::::::::
- **x** (Tensor) - 输入的 Tensor。维度为多维,数据类型为 bool、int32、int64、float32 或 float64。别名 ``input``。
- **axis** (list|tuple|int) - 需要翻转的轴。当 axis 是 int 型时,且 axis<0,实际的计算维度为 ndim(x) + axis;axis 是 list 或 tuple 时,``axis[i] < 0`` 时,实际的计算维度为 ndim(x) + axis[i],其中 i 为 axis 的索引。别名 ``dims``。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
Tensor,在指定 axis 上翻转后的 Tensor,与输入 x 数据类型相同。
代码示例
::::::::::::
COPY-FROM: paddle.flip
File: docs/api/paddle/floor__cn.rst
.. cn_api_paddle_floor:
floor\_
.. py:function:: paddle.floor_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_floor API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/floor_cn.rst
.. _cn_api_paddle_floor:
floor
.. py:function:: paddle.floor(x, name=None, *, out=None)
向下取整函数。
.. math::
out = \left \lfloor x \right \rfloor
参数
::::::::::::
- **x** - 输入为多维 Tensor。数据类型支持 float32、float64、float16、bfloat16、uint8、int8、int16、int32、int64。别名 ``input``。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。关键字参数
:::::::::
- **out** (Tensor,可选) - 输出 Tensor,若不为 ``None``,计算结果将保存在该 Tensor 中,默认值为 ``None``。返回
::::::::::::
输出为 Tensor,与 x 维度相同、数据类型相同。
代码示例
::::::::::::
COPY-FROM: paddle.floor
File: docs/api/paddle/floor_divide__cn.rst
.. cn_api_paddle_floor_divide:
floor_divide\_
.. py:function:: paddle.floor_divide_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_floor_divide API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
.. note::
别名支持: 参数名 input 可替代 x,参数名 other 可替代 y,如 floor_divide_(input=tensor_x, other=tensor_y) 等价于 floor_divide_(x=tensor_x, y=tensor_y)。
File: docs/api/paddle/floor_divide_cn.rst
.. _cn_api_paddle_floor_divide:
floor_divide
.. py:function:: paddle.floor_divide(x, y, name=None)
逐元素整除算子,将输入 x 与输入 y 逐元素整除(商被朝 -inf 方向舍入到最接近的整数值),并将各个位置的输出元素保存到返回结果中。
.. note::
输入 x 与输入 y 必须和广播为相同形状,关于广播规则,请参见 Tensor 介绍_ .
.. _Tensor 介绍: ../../guides/beginner/tensor_cn.html#id7等式为:
.. math::
Out = floor(X / Y)
- :math:
X:多维 Tensor。 - :math:
Y:多维 Tensor。
.. note::
别名支持: 参数名 input 可替代 x 和 other 可替代 y,如 input=tensor_x 等价于 x=tensor_x, other=tensor_y 等价于 y=tensor_y。
参数
:::::::::
- x (Tensor) - 多维 Tensor。数据类型为 int8 int16 int32 int64 float32 float64 float16 或 bfloat16。
别名: input
- y (Tensor) - 多维 Tensor。数据类型为 int8 int16 int32 int64 float32 float64 float16 或 bfloat16。
别名: other
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
- out (Tensor,可选) - 指定输出结果的 Tensor,默认值为 None。
返回
:::::::::
多维 Tensor,数据类型与 x 相同,维度为广播后的形状。
代码示例
:::::::::
COPY-FROM: paddle.floor_divide
File: docs/api/paddle/flops_cn.rst
.. _cn_api_paddle_flops:
flops
.. py:function:: paddle.flops(net, input_size, custom_ops=None, print_detail=False)
打印网络的基础结构和参数信息。
参数
:::::::::
- net (paddle.nn.Layer|paddle.static.Program) - 网络实例,必须是 paddle.nn.Layer 的子类或者静态图下的 paddle.static.Program。
- input_size (list) - 输入 Tensor 的大小。注意:仅支持 batch_size=1。
- custom_ops (dict,可选) - 字典,用于实现对自定义网络层的统计。字典的 key 为自定义网络层的 class,value 为统计网络层 flops 的函数,函数实现方法见示例代码。此参数仅在
net为 paddle.nn.Layer 时生效。默认值:None。 - print_detail (bool,可选) - bool 值,用于控制是否打印每个网络层的细节。默认值:False。
返回
:::::::::
int,网络模型的计算量。
代码示例
:::::::::
COPY-FROM: paddle.flops
File: docs/api/paddle/fmax_cn.rst
.. _cn_api_paddle_fmax:
fmax
.. py:function:: paddle.fmax(x, y, name=None, *, out=None)
比较两个 Tensor 对应位置的元素,返回一个包含该元素最大值的新 Tensor。如果两个元素其中一个是 nan 值,则直接返回另一个值,如果两者都是 nan 值,则返回第一个 nan 值。
等式是:
.. math::
out = fmax(x, y)
.. note::
paddle.fmax 遵守 broadcasting,如您想了解更多,请参见 Tensor 介绍_ .
.. _Tensor 介绍: ../../guides/beginner/tensor_cn.html#id7
参数
:::::::::
- x (Tensor)- 输入的 Tensor。数据类型为
bfloat16、float16、float32、float64、int32或int64。别名input。 - y (Tensor)- 输入的 Tensor。数据类型为
bfloat16、float16、float32、float64、int32或int64。别名other。 - name (str,可选) - 具体用法请参见 :ref:
api_guide_Name,一般无需设置,默认值为 None。
关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为
None,计算结果将保存在该 Tensor 中,默认值为None。
返回
:::::::::
Tensor,存储运算后的结果。如果 x 和 y 有不同的 shape 且是可以广播的,返回 Tensor 的 shape 是 x 和 y 经过广播后的 shape。如果 x 和 y 有相同的 shape,返回 Tensor 的 shape 与 x,y 相同。
代码示例
::::::::::
COPY-FROM: paddle.fmax
File: docs/api/paddle/fmin_cn.rst
.. _cn_api_paddle_fmin:
fmin
.. py:function:: paddle.fmin(x, y, name=None, *, out=None)
比较两个 Tensor 对应位置的元素,返回一个包含该元素最小值的新 Tensor。如果两个元素其中一个是 nan 值,则直接返回另一个值,如果两者都是 nan 值,则返回第一个 nan 值。
等式是:
.. math::
out = fmin(x, y)
.. note::
paddle.fmin 遵守 broadcasting,如您想了解更多,请参见 Tensor 介绍_ .
.. _Tensor 介绍: ../../guides/beginner/tensor_cn.html#id7
参数
:::::::::
- x (Tensor)- 输入的 Tensor。数据类型为
bfloat16、float16、float32、float64、int32或int64。别名input。 - y (Tensor)- 输入的 Tensor。数据类型为
bfloat16、float16、float32、float64、int32或int64。别名other。 - name (str,可选) - 具体用法请参见 :ref:
api_guide_Name,一般无需设置,默认值为 None。
关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为
None,计算结果将保存在该 Tensor 中,默认值为None。
返回
:::::::::
Tensor,存储运算后的结果。如果 x 和 y 有不同的 shape 且是可以广播的,返回 Tensor 的 shape 是 x 和 y 经过广播后的 shape。如果 x 和 y 有相同的 shape,返回 Tensor 的 shape 与 x,y 相同。
代码示例
::::::::::
COPY-FROM: paddle.fmin
File: docs/api/paddle/frac__cn.rst
.. cn_api_paddle_frac:
frac\_
.. py:function:: paddle.frac_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_frac API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/frac_cn.rst
.. _cn_api_paddle_frac:
frac
.. py:function:: paddle.frac(x, name=None, *, out=None)
得到输入 Tensor 的小数部分。
参数
:::::::::
- x (Tensor):输入变量,类型为 Tensor,支持 int32、int64、float32、float64 数据类型。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
- out (Tensor,可选)- 输出的结果。该参数为仅关键字参数,默认值为 None。
返回
:::::::::
- Tensor (Tensor),输入矩阵只保留小数部分的结果。
代码示例
:::::::::
COPY-FROM: paddle.frac
File: docs/api/paddle/frexp_cn.rst
.. _cn_api_paddle_frexp:
frexp
.. py:function:: paddle.frexp(x, name=None, *, out=None)
用于把一个浮点数分解为尾数和指数的函数,返回一个尾数 Tensor 和一个指数 Tensor。
参数
::::::::::
- x (Tensor) – 输入是一个多维的 Tensor,它的数据类型可以是 float32,float64。别名 input。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name ,一般无需设置,默认值为 None。
关键字参数
::::::::::
- out (tuple[Tensor, Tensor],可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 元组中,默认值为 None。
返回
::::::::::
mantissa(Tensor):分解后的尾数,类型为 Tensor,形状和原输入的形状一致。
exponent(Tensor):分解后的指数,类型为 Tensor,形状和原输入的形状一致。代码示例
::::::::::
COPY-FROM: paddle.frexp
File: docs/api/paddle/from_dlpack_cn.rst
[Binary file]
File: docs/api/paddle/full_cn.rst
.. _cn_api_paddle_full:
full
.. py:function:: paddle.full(shape, fill_value, dtype=None, name=None, *, out=None, device=None, requires_grad=False, pin_memory=False)
创建形状大小为 shape 并且数据类型为 dtype 的 Tensor,其中元素值均为 fill_value 。
.. note::
别名支持: 参数名 size 可替代 shape,如 full(size=[2, 3], …) 等价于 full(shape=[2, 3], …) 。
参数
::::::::::::
- **shape** (list|tuple|Tensor|*shape) - 生成的 Tensor 的形状。数据类型为 int32 或 int64。
如果 ``shape`` 是 list、tuple,则其中的元素可以是 int,或者是形状为 [] 且数据类型为 int32、int64 的 0-D Tensor。
如果 ``shape`` 是 Tensor,则是数据类型为 int32、int64 的 1-D Tensor,表示一个列表。
如果 ``shape`` 是 \*shape,则可以直接以可变参数的形式传入多个整数(例如 ``randn(2, 3)``)。
该参数的别名为 ``size``。
- **fill_value** (bool|float|int|Tensor) - 用于初始化输出 Tensor 的常量数据的值。如果 fill_value 是一个 Tensor ,它应该是一个表示标量的 0-D Tensor。注意:该参数不可超过输出变量数据类型的表示范围。
- **dtype** (str|paddle.dtype|np.dtype,可选)- 输出变量的数据类型,可以是 float16、float32、float64、int32、int64。如果 dtype 为 None,则创建的 Tensor 的数据类型为 float32。默认值为 None。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。关键字参数
::::::::::::
- out (Tensor,可选) - 用于存储结果的 Tensor。若指定,将直接写入该 Tensor,默认值为 None。
- device (PlaceLike|None,可选) - 期望创建 Tensor 所在的设备。默认值为 None,表示使用当前全局设备(可通过 paddle.device.set_device 设置)。
- requires_grad (bool,可选) - 是否需要为返回的 Tensor 记录梯度信息。默认值为 False。
- pin_memory (bool,可选) - 若为 True,返回的 Tensor 将分配在锁页内存中。默认值为 False。
返回
::::::::::::
返回一个存储结果的 Tensor,数据类型和 dtype 相同。
代码示例
::::::::::::
COPY-FROM: paddle.full
File: docs/api/paddle/full_like_cn.rst
.. _cn_api_paddle_full_like:
full_like
.. py:function:: paddle.full_like(x, fill_value, dtype=None, name=None, *, device=None, requires_grad=False, pin_memory=False)
创建一个和 x 具有相同的形状并且数据类型为 dtype 的 Tensor,其中元素值均为 fill_value,当 dtype 为 None 的时候,Tensor 数据类型和输入 x 相同。
.. note::
别名支持: 参数名 input 可替代 x,如 input=tensor_x 等价于 x=tensor_x。
参数
::::::::::::
- **x** (Tensor) – 输入 Tensor,输出 Tensor 和 x 具有相同的形状,x 的数据类型可以是 bool、float16、float32、float64、int32、int64。
别名: ``input``
- **fill_value** (bool|float|int) - 用于初始化输出 Tensor 的常量数据的值。注意:该参数不可超过输出变量数据类型的表示范围。
- **dtype** (str|paddle.dtype|np.dtype,可选) - 输出变量的数据类型。若参数为 None,则输出变量的数据类型和输入变量相同,默认值为 None。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。关键字参数
::::::::::::
- device (PlaceLike|None,可选) - 期望创建 Tensor 所在的设备。若为 None,则与 x 保持一致。
- requires_grad (bool,可选) - 是否需要为返回的 Tensor 记录梯度信息。默认值为 False。
- pin_memory (bool,可选) - 若为 True,返回的 Tensor 将分配在锁页内存中。默认值为 False。
返回
::::::::::::
返回一个根据 x 、fill_value 、 dtype 创建的 Tensor。
代码示例
::::::::::::
COPY-FROM: paddle.full_like
File: docs/api/paddle/gammainc__cn.rst
.. cn_api_paddle_gammainc:
gammainc\_
.. py:function:: paddle.gammainc_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_gammainc API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/gammainc_cn.rst
.. _cn_api_paddle_gammainc:
gammainc
.. py:function:: paddle.gammainc(x, y, name=None)
计算正则化下不完全伽马函数。
.. math::
P(x, y) = \frac{1}{\Gamma(x)} \int_{0}^{y} t^{x-1} e^{-t} dt
参数
::::::::::::
- **x** - 非负参数 Tensor。数据类型必须为 float32, float64。
- **y** - 正参数 Tensor。数据类型必须为 float32, float64。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
输出为 Tensor,计算的正则化下不完全伽马函数值。
代码示例
::::::::::::
COPY-FROM: paddle.gammainc
File: docs/api/paddle/gammaincc__cn.rst
.. cn_api_paddle_gammaincc:
gammaincc\_
.. py:function:: paddle.gammaincc_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_gammaincc API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/gammaincc_cn.rst
.. _cn_api_paddle_gammaincc:
gammaincc
.. py:function:: paddle.gammaincc(x, y, name=None)
计算正则化上不完全伽马函数。
.. math::
Q(x, y) = \frac{1}{\Gamma(x)} \int_{y}^{\infty} t^{x-1} e^{-t} dt
参数
::::::::::::
- **x** - 非负参数 Tensor。数据类型必须为 float32, float64。
- **y** - 正参数 Tensor。数据类型必须为 float32, float64。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
输出为 Tensor,计算的正则化上不完全伽马函数值。
代码示例
::::::::::::
COPY-FROM: paddle.gammaincc
File: docs/api/paddle/gammaln__cn.rst
.. cn_api_paddle_gammaln:
gammaln\_
.. py:function:: paddle.gammaln_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_gammaln API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/gammaln_cn.rst
.. _cn_api_paddle_gammaln:
gammaln
.. py:function:: paddle.gammaln(x, name=None)
逐元素计算伽马函数的绝对值的自然对数。
参数
::::::::::::
- **x** - 输入 Tensor。数据类型必须为 float16, float32, float64, bfloat16。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
输出为 Tensor,与 x 维度相同、数据类型相同。
代码示例
::::::::::::
COPY-FROM: paddle.gammaln
File: docs/api/paddle/gather_cn.rst
.. _cn_api_paddle_gather:
gather
.. caution::
本接口根据输入参数的不同,包含两种不同的功能。
下面列举的两种功能参数输入方式 **互斥**,混用非公共的参数输入方法将会导致报错,请谨慎使用。=====
.. py:function:: paddle.gather(x, index, axis=None, name=None)
根据索引 index 获取输入 x 的指定 axis 维度的条目,并将它们拼接在一起。
.. code-block:: text
Given:
X = [[1, 2],
[3, 4],
[5, 6]]
Index = [1, 2]
axis = 0
Then:
Out = [[3, 4],
[5, 6]]下面展示了将一个形状为[3,2]的向量通过 gather 操作,沿着 axis = 0 维度,根据索引 Index = [1, 2] 获取对应的二维张量的例子。若索引为零维,则返回结果为一维张量,例如 Index = 0 ,沿着 axis = 0 维度,则返回位于图片上方的一维张量。
.. image:: ../../images/api_legend/gather.png
:width: 600
:alt: 图例
参数
::::::::::::
- x (Tensor) - 输入 Tensor,秩 rank >= 1,支持的数据类型包括 int32、int64、float32、float64、complex64、complex128 和 uint8 (CPU)、float16(GPU) 。
- index (Tensor) - 索引 Tensor,秩 rank = 0 或者 rank = 1,数据类型为 int32 或 int64。
- axis (Tensor) - 指定 index 获取输入的维度,axis 的类型可以是 int 或者 Tensor,当 axis 为 Tensor 的时候其数据类型为 int32 或者 int64。默认值为 None,当 axis 为 None 的时候其值为 0。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
::::::::::::
Tensor,当 index 为一维 Tensor 时,返回和输入 Tensor 的形状相同的 Tensor。当 index 为零维 Tensor 时,返回 Tensor 相对于输入 Tensor 会降维, axis 指向的维度会被降维。
代码示例
::::::::::::
COPY-FROM: paddle.gather
=====
.. py:function:: paddle.gather(input, dim, index, out=None)
PyTorch 兼容的 gather 操作:根据索引 index 获取输入 input 的指定 dim 维度的条目,并将它们拼接在一起。行为与 :ref:cn_api_paddle_take_along_axis 在 broadcast=False 情况下一致。
接口对比可见 【torch 参数更多】torch.gather_ 。
.. _【torch 参数更多】torch.gather: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/model_convert/convert_from_pytorch/api_difference/torch/torch.gather.html
参数
::::::::::::
- input (Tensor) - 输入 Tensor,支持的数据类型包括 int32、int64、float32、float64、int16、uint8、float16(GPU)以及 bfloat16(GPU) 。
- dim (int) - 指定 index 获取输入的维度,dim 的类型可以是 int 或者。
- index (Tensor) - 索引 Tensor,index 张量的各维度需要小于等于 input 张量的各维度(除 dim 维度外),且值需要在 input.shape[dim] 范围内。数据类型为 int32 或 int64。
- out (Tensor,可选) - 用于引用式传入输出值,注意:动态图下 out 可以是任意 Tensor,默认值为 None。
.. caution::
本接口没有实现 PyTorch 的 ``sparse_grad`` 参数!梯度默认是稠密的,等效于 ``sparse_grad=False``。返回
::::::::::::
Tensor,与 input 有数据类型,与 index 有相同的形状。
代码示例
:::::::::
见 :ref:cn_api_paddle_take_along_axis 的代码示例。
File: docs/api/paddle/gather_nd_cn.rst
.. _cn_api_paddle_gather_nd:
gather_nd
.. py:function:: paddle.gather_nd(x, index, name=None)
:code:gather 的高维推广,并且支持多轴同时索引。:code:index 是一个 K 维度的 Tensor,它可以认为是从 :code:x 中取 K-1 维 Tensor,每一个元素是一个切片:
.. math::
output[(i_0, ..., i_{K-2})] = x[index[(i_0, ..., i_{K-2})]]
显然,:code:index.shape[-1] <= x.rank 并且输出 Tensor 的维度是 :code:index.shape[:-1] + x.shape[index.shape[-1]:] 。
示例:
::
给定:
x = [[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]]
x.shape = (2, 3, 4)
- 案例 1:
index = [[1]]
gather_nd(x, index)
= [x[1, :, :]]
= [[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]
- 案例 2:
index = [[0,2]]
gather_nd(x, index)
= [x[0, 2, :]]
= [8, 9, 10, 11]
- 案例 3:
index = [[1, 2, 3]]
gather_nd(x, index)
= [x[1, 2, 3]]
= [23]示例图解说明:
下图展示了示例中的情形——一个形状为[2,3,4]的三维张量通过 gather_nd 操作分别输出三个不同的张量。通过比较,可以看出不同 index 下输出张量的差别。
.. figure:: ../../images/api_legend/gather_nd.png
:width: 761
:alt: 示例图示
:align: center参数
::::::::::::
- **x** (Tensor) - 输入 Tensor,数据类型可以是 int32、int64、float16、float32、float64、bool。
- **index** (Tensor) - 输入的索引 Tensor,其数据类型 int32 或者 int64。它的维度 :code:`index.rank` 必须大于 1,并且 :code:`index.shape[-1] <= x.rank` 。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
shape 为 index.shape[:-1] + x.shape[index.shape[-1]:]的 Tensor,数据类型与 :code:x 一致。
代码示例
::::::::::::
COPY-FROM: paddle.gather_nd
File: docs/api/paddle/gcd__cn.rst
.. cn_api_paddle_gcd:
gcd\_
.. py:function:: paddle.gcd_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_gcd API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/gcd_cn.rst
.. _cn_api_paddle_gcd:
gcd
.. py:function:: paddle.gcd(x, y, name=None)
计算两个输入的按元素绝对值的最大公约数,输入必须是整型。
.. note::
gcd(0,0)=0, gcd(0, y)=|y|
如果 x 和 y 的 shape 不一致,会对两个 shape 进行广播操作,得到一致的 shape(并作为输出结果的 shape),
请参见 `Tensor 介绍`_ .
.. _Tensor 介绍: ../../guides/beginner/tensor_cn.html#id7参数
:::::::::
- **x** (Tensor) - 输入的 Tensor,数据类型为:int32,int64。支持别名 ``input`` 。
- **y** (Tensor) - 输入的 Tensor,数据类型为:int32,int64。支持别名 ``other`` 。
- **name** (str,可选) - 操作的名称(可选,默认值为 None)。更多信息请参见 :ref:`api_guide_Name`。返回
:::::::::
输出 Tensor,与输入数据类型相同。
代码示例
:::::::::
COPY-FROM: paddle.gcd
File: docs/api/paddle/geometric__cn.rst
.. cn_api_paddle_geometric:
geometric\_
.. py:function:: paddle.geometric_(x, probs, name=None)
使用从几何分布中抽取的数据填充 Tensor。
参数
::::::::::::
- **x** (Tensor) - 被填充的 Tensor ,数据类型为: float32、float64。
- **probs** (float | Tensor) - 输入的概率参数, probs 的值必须为正,数据类型为 float、Tensor。当该参数类型为 Tensor 时, probs 代表每次试验成功的概率。别名: ``p``。
- **name** (str ,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
填充了服从几何分布随机数的输入 Tensor。
代码示例
::::::::::::
COPY-FROM: paddle.geometric_
File: docs/api/paddle/ger_cn.rst
.. _cn_api_paddle_ger:
ger
.. py:function:: paddle.ger(x, y, name=None, *, out=None)
outer 的别名,请参考 :ref:cn_api_paddle_outer。
File: docs/api/paddle/get_autocast_dtype_cn.rst
.. _cn_api_paddle_get_autocast_dtype:
get_autocast_dtype
.. py:function:: paddle.get_autocast_dtype(device_type=None)
获取当前上下文中自动混合精度的默认数据类型。
参数
::::::::::::
- **device_type** (str, 可选) - 设备类型,默认为 None。注意:在 PaddlePaddle 中所有设备共享同一套自动混合精度配置,实际返回值与设备类型无关。返回
::::::::::::
字符串,当前上下文中自动混合精度的默认数据类型。
代码示例
::::::::::::
COPY-FROM: paddle.get_autocast_gpu_dtype
File: docs/api/paddle/get_autocast_gpu_dtype_cn.rst
.. _cn_api_paddle_get_autocast_gpu_dtype:
get_autocast_gpu_dtype
.. py:function:: paddle.get_autocast_gpu_dtype(device_type=None)
get_autocast_dtype 的别名,请参考 :ref:cn_api_paddle_get_autocast_dtype。
File: docs/api/paddle/get_cuda_rng_state_cn.rst
.. _cn_api_paddle_get_cuda_rng_state:
get_cuda_rng_state
.. py:function:: paddle.get_cuda_rng_state()
获取 cuda 随机数生成器的状态信息。
返回
::::::::::::
GeneratorState:对象。代码示例
::::::::::::
COPY-FROM: paddle.get_cuda_rng_state
File: docs/api/paddle/get_default_device_cn.rst
.. _cn_api_paddle_get_default_device:
get_default_device
.. py:function:: paddle.get_default_device()
获取程序当前运行的全局设备信息。
返回一个表示当前设备的字符串,格式可能是:
- 'cpu'
- 'gpu:x' (CUDA 设备)
- 'xpu:x' (XPU 设备)
- 'npu:x' (NPU 设备)
如果全局设备未明确设置,将根据以下规则返回:
- 当 CUDA 可用时返回 'gpu:x'
- 当 CUDA 不可用时返回 'cpu'
返回
:::::::::
str: 表示当前设备的字符串
代码示例
:::::::::
.. code-block:: python
>>> import paddle
>>> device = paddle.get_default_device()File: docs/api/paddle/get_default_dtype_cn.rst
.. _cn_api_paddle_get_default_dtype:
get_default_dtype
.. py:function:: paddle.get_default_dtype()
得到当前全局的 dtype。该值初始是 float32。
返回
::::::::::::
string,这个全局 dtype 仅支持 float16、float32、float64。
代码示例
::::::::::::
COPY-FROM: paddle.get_default_dtype
File: docs/api/paddle/get_device_module_cn.rst
.. _cn_api_paddle_get_device_module:
get_device_module
.. py:function:: paddle.get_device_module(device=None)
获取指定设备对应的 Paddle 模块。
参数
:::::::::
device (_CustomPlaceLike, 可选) - 要查询的设备,可以是以下类型之一:
- paddle.Place 对象 (例如 paddle.CUDAPlace(0))
- 字符串 (例如 "gpu:0", "xpu", "npu")
- 整数 (设备索引,例如 0 -> "gpu:0")
- None (使用当前预期设备)
返回
:::::::::
module: 对应的 Paddle 设备模块 (例如 paddle.cuda, paddle.device.xpu)
代码示例
:::::::::
.. code-block:: python
>>> import paddle
>>> paddle.get_device_module("gpu:0")
<module 'paddle.cuda' ...>File: docs/api/paddle/get_flags_cn.rst
.. _cn_api_paddle_get_flags:
get_flags
.. py:function:: paddle.get_flags(flags)
获取指定的 Paddle 环境变量 FLAGS 状态。详情请查看 :ref:cn_guides_flags_flags。
参数
::::::::::::
- **flags** (list of FLAGS [*]) - 想要获取的 FLAGS 标志列表。返回
::::::::::::
Flag 的值。
代码示例
::::::::::::
COPY-FROM: paddle.get_flags
File: docs/api/paddle/get_rng_state_cn.rst
.. _cn_api_paddle_get_rng_state:
get_rng_state
.. py:function:: paddle.get_rng_state(device=None)
获取指定设备的随机数生成器的所有随机状态。
参数
::::::::::::
- device (str) - 此参数决定了具体的运行设备。可以是 cpu、gpu、xpu。默认值为 None。如果为 None,则返回当前设备(由 set_device 指定)的生成器。
返回
::::::::::::
- GeneratorState:对象。
代码示例
::::::::::::
COPY-FROM: paddle.get_rng_state
File: docs/api/paddle/grad_cn.rst
[Binary file]
File: docs/api/paddle/greater_equal__cn.rst
.. cn_api_paddle_greater_equal:
greater\_equal\_
.. py:function:: paddle.greater_equal_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_greater_equal API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/greater_equal_cn.rst
.. _cn_api_paddle_greater_equal:
greater_equal
.. py:function:: paddle.greater_equal(x, y, name=None)
逐元素地返回 :math:x >= y 的逻辑值,相同位置前者输入大于等于后者输入返回 True,否则返回 False。使用重载算子 >= 可以有相同的计算函数效果。
.. note::
输出的结果不返回梯度。
参数
::::::::::::
- **x** (Tensor) - 输入 Tensor,支持的数据类型包括 bool、bfloat16、float16、float32、float64、uint8、int8、int16、int32、int64。
- **y** (Tensor) - 输入 Tensor,支持的数据类型包括 bool、bfloat16、float16、float32、float64、uint8、int8、int16、int32、int64。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
输出结果的 Tensor,shape 和输入一致,数据类型为 bool。
代码示例
::::::::::::
COPY-FROM: paddle.greater_equal
File: docs/api/paddle/greater_than__cn.rst
.. cn_api_paddle_greater_than:
greater\_than\_
.. py:function:: paddle.greater_than_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_greater_than API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/greater_than_cn.rst
.. _cn_api_paddle_greater_than:
greater_than
.. py:function:: paddle.greater_than(x, y, name=None)
返回 :math:x>y 逐元素比较 x 和 y 是否相等,相同位置前者输入大于等于后者输入则返回 True,否则返回 False。使用重载算子 > 可以有相同的计算函数效果。
.. note::
输出的结果不返回梯度。
参数
:::::::::
- x (Tensor) - 输入 Tensor,支持的数据类型包括 bool、bfloat16、float16、float32、float64、uint8、int8、int16、int32、int64。
- y (Tensor) - 输入 Tensor,支持的数据类型包括 bool、bfloat16、float16、float32、float64、uint8、int8、int16、int32、int64。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::
Tensor,输出结果,shape 和输入一致,Tensor 数据类型为 bool。
代码示例
:::::::::
COPY-FROM: paddle.greater_than
File: docs/api/paddle/gt_cn.rst
.. _cn_api_paddle_gt:
gt
.. py:function:: paddle.gt(x, y, name=None, *, out=None)
greater_than 的别名,请参考 :ref:cn_api_paddle_greater_than。
File: docs/api/paddle/heaviside_cn.rst
.. _cn_api_paddle_heaviside:
heaviside
.. py:function:: paddle.heaviside(x, y, name=None, *, out=None)
为 :attr:x 中的每个元素计算由 :attr:y 中相对应元素决定的赫维赛德阶跃函数,其计算公式为
.. math::
\mathrm{heaviside}(x, y)=
\left{
\begin{array}{lcl}
0,& &\text{if } \ x < 0, \
y,& &\text{if } \ x = 0, \
1,& &\text{if } \ x > 0.
\end{array}
\right.
.. note::
paddle.heaviside 遵守广播机制,如您想了解更多,请参见 Tensor 介绍_ .
.. _Tensor 介绍: ../../guides/beginner/tensor_cn.html#id7
参数
:::::::::
- x (Tensor) - 赫维赛德阶跃函数的输入 Tensor。数据类型为 bfloat16、float16、float32、float64、int32 或 int64。别名
input。 - y (Tensor) - 决定了一个赫维赛德阶跃函数的 Tensor。数据类型为 bfloat16、float16、float32、float64、int32 或 int64。别名
values。 - name (str,可选) - 具体用法请参见 :ref:
api_guide_Name,一般无需设置,默认值为 None。
关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为
None,计算结果将保存在该 Tensor 中,默认值为None。
返回
:::::::::
Tensor,存储运算后的结果。如果 :attr:x 和 :attr:y 有不同的形状且是可以广播的,那么返回 Tensor 的形状是 :attr:x 和 :attr:y 经过广播后的形状。如果 :attr:x 和 :attr:y 有相同的形状,那么返回 Tensor 的形状与 :attr:x 和 :attr:y 相同。
代码示例
::::::::::
COPY-FROM: paddle.heaviside
File: docs/api/paddle/histc_cn.rst
.. _cn_api_paddle_histc:
histc
.. py:function:: paddle.histc(input, bins=100, min=0.0, max=0.0, name=None, *, out=None)
计算 Tensor 的直方图。
元素被分配到 min 和 max 之间的等宽区间中(包含边界)。如果 min 和 max 都为零,则使用数据的最小值和最大值。
参数
:::::::::
- input (Tensor) - 输入 Tensor。
- bins (int,可选) - 直方图区间数,默认值为 100。
- min (float,可选) - 范围的下端(包含),默认值为 0.0。
- max (float,可选) - 范围的上端(包含),默认值为 0.0。
- name (str,可选) - 操作名称,默认值为 None。
关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
:::::::::
Tensor:直方图 Tensor,数据类型为 float32。
代码示例
:::::::::
COPY-FROM: paddle.histc
File: docs/api/paddle/histogram_bin_edges_cn.rst
.. _cn_api_paddle_histogram_bin_edges:
histogram_bin_edges
.. py:function:: paddle.histogram_bin_edges(input, bins=100, min=0.0, max=0.0, name=None)
只返回在计算 input 的直方图时所使用的 bins 的边界值 bin_edges。如果 min 和 max 都为 0.0,则利用数据中的最大最小值作为边界。
参数
::::::::::::
- **input** (Tensor) - 输入 Tensor。维度为多维,数据类型为 int32、int64、float32 或 float64。
- **bins** (int,可选) - 直方图 bins(直条)的个数,默认为 100。
- **min** (float,可选) - range 的下边界(包含),默认为 0.0。
- **max** (float,可选) - range 的上边界(包含),默认为 0.0。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
Tensor,计算直方图时所使用的边界值 bin_edges,返回的数据类型为 float32。
代码示例
::::::::::::
COPY-FROM: paddle.histogram_bin_edges
File: docs/api/paddle/histogram_cn.rst
.. _cn_api_paddle_histogram:
histogram
.. py:function:: paddle.histogram(input, bins=100, min=0.0, max=0.0, weight=None, density=False, name=None)
计算输入 Tensor 的直方图。以 min 和 max 为 range 边界,将其均分成 bins 个直条,然后将排序好的数据划分到各个直条(bins)中。如果 min 和 max 都为 0.0,则利用数据中的最大最小值作为边界。
参数
::::::::::::
- **input** (Tensor) - 输入 Tensor。维度为多维,数据类型为 int32、int64、float32 或 float64。
- **bins** (int,可选) - 直方图 bins(直条)的个数,默认为 100。
- **min** (float,可选) - range 的下边界(包含),默认为 0.0。
- **max** (float,可选) - range 的上边界(包含),默认为 0.0。
- **weight** (Tensor,可选) - 权重 Tensor,维度和 input 相同。如果提供,输入中的每个值都将以对应的权重值进行计数(而不是 1)。默认为 None。
- **density** (bool,可选) - 如果为 False,则返回直方图中每个 bin 的计数。如果为 True,则返回直方图中每个 bin 经过归一化后的概率密度函数的值,使得直方图的积分(即所有 bin 的面积)等于 1。默认为 False。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
Tensor,维度为(nbins,)。如果 density 为 True 或者 weight 不为 None,则返回的 Tensor 的数据类型为 float32;否则为 int64。
代码示例
::::::::::::
COPY-FROM: paddle.histogram
File: docs/api/paddle/histogramdd_cn.rst
.. _cn_api_paddle_histogramdd:
histogramdd
.. py:function:: paddle.histogramdd(x, bins=10, ranges=None, density=False, weights=None, name=None)
计算输入多维 Tensor 的直方图。将最内维度大小为 N 的输入张量的元素解释为 N 维点的集合。将每个点映射到一组 N 维 bin 中,并返回每个 bin 中的点数(或总权重)
输入 x 必须是具有至少 2 个维度的张量。如果输入具有形状 (M,N) 则其 M 行中的每一行定义 N 维空间中的一个点。如果输入有三个或多个维度,则除最后一个维度外的所有维度都将被展平。
参数
::::::::::::
- **x** (Tensor) - 输入多维 Tensor 。
- **bins** (Tensor[]|int[]|int) - 如果为 Tensor 数组,则表示所有 bin 边界。如果为 int 数组,则表示每个维度中等宽 bin 的数量。如果为 int,则表示所有维度的等宽 bin 数量。默认值为 10 ,表示所有维度的等宽 bin 数量为 10 个。
- **ranges** (float[], 可选) - 表示每个维度中最左边和最右边的 bin 边界。如果为 None ,则将每个尺寸的最小值和最大值设置为最左边和最右边。默认值为 None ,表示自动根据最大值与最小值计算 bin 的边界。
- **density** (bool,可选) - 表示是否计算 density ,如果为 False,结果将包含每个 bin 中的计数(或权重)。如果为 True,则将每个计数(权重)除以总计数(总权重),然后再除以相关 bin 的宽度。默认值为 False ,表示不计算 density 。
- **weights** (Tensor,可选) - 表示权重。如果传递 Tensor ,则输入中的每个 N 维坐标将其相关权重贡献给其 bin 的结果。权重应具有与输入张量相同的形状,但不包括其最内维度 N。默认情况下,输入中的每个值的权重为 1 。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
包含直方图值的 N 维张量,包含 bin 边界信息的 N 个 1D tensor 的序列。
代码示例
::::::::::::
COPY-FROM: paddle.histogramdd
File: docs/api/paddle/hsplit_cn.rst
.. _cn_api_paddle_hsplit:
hsplit
.. py:function:: paddle.hsplit(x, num_or_indices, name=None)
hsplit 全称 Horizontal Split ,即水平分割,将输入 Tensor 沿着水平轴分割成多个子 Tensor,存在以下两种情况:
当 x 的维度等于 1 时,等价于将 :ref:
cn_api_paddle_tensor_splitAPI 的参数 axis 固定为 0;.. image:: ../../images/api_legend/hsplit/hsplit-1.png
:alt: 当 x 的维度等于 1 时当 x 的维度大于 1 时,等价于将 :ref:
cn_api_paddle_tensor_splitAPI 的参数 axis 固定为 1。.. image:: ../../images/api_legend/hsplit/hsplit-2.png
:alt: 当 x 的维度大于 1 时
参数
:::::::::
- x (Tensor) - 输入变量,数据类型为 bool、bfloat16、float16、float32、float64、uint8、int8、int32、int64 的多维 Tensor,其维度必须大于 0。
- num_or_indices (int|list|tuple) - 如果 num_or_indices 是一个整数 n ,则 x 拆分为 n 部分。如果 num_or_indices 是整数索引的列表或元组,则在每个索引处分割 x 。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::
list[Tensor],分割后的 Tensor 列表。
代码示例
:::::::::
COPY-FROM: paddle.hsplit
File: docs/api/paddle/hstack_cn.rst
.. _cn_api_paddle_hstack:
hstack
.. py:function:: paddle.hstack(x, name=None, *, out=None)
沿水平轴堆叠输入 x 中的所有张量。所有张量必须具有相同的数据类型。
参数
::::::::::::
- **x** (list[Tensor]|tuple[Tensor]) - 输入 ``x`` 可以是张量的 list 或 tuple, ``x`` 中张量的数据类型必须相同。支持的数据类型: ``float16`` 、 ``float32`` 、 ``float64`` 、 ``int8`` 、 ``int32`` 、 ``int64`` 或 ``bfloat16`` 。别名 ``tensors``。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。关键字参数
::::::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
::::::::::::
Tensor,与输入数据类型相同的堆叠张量。
也可以参考下方的图示来理解 hstack 是如何对张量进行变换的。
.. image:: ../../images/api_legend/hstack.png
:width: 500
:alt: 图例
代码示例
::::::::::::
COPY-FROM: paddle.hstack
File: docs/api/paddle/hypot__cn.rst
.. cn_api_paddle_hypot:
hypot\_
.. py:function:: paddle.hypot_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_hypot API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/hypot_cn.rst
[Binary file]
File: docs/api/paddle/i0__cn.rst
.. cn_api_paddle_i0:
i0\_
.. py:function:: paddle.i0_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_i0 API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/i0_cn.rst
.. _cn_api_paddle_i0:
i0
.. py:function:: paddle.i0(x, name=None)
对于给定 x 计算其每个元素的第一类零阶修正贝塞尔曲线函数,其中输入 x 大小无特殊限制。返回一个第一类零阶修正贝塞尔曲线函数上的 Tensor。
.. math::
I_0(x)=\sum^{\infty}_{k=0}\frac{(x^2/4)^k}{(k!)^2}
参数
::::::::::
- x (Tensor) – 输入是一个多维的 Tensor,它的数据类型可以是 float32,float64。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name ,一般无需设置,默认值为 None。
关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
::::::::::
- Tensor (Tensor):在 x 处的第一类零阶修正贝塞尔曲线函数的值。
代码示例
::::::::::
COPY-FROM: paddle.i0
File: docs/api/paddle/i0e_cn.rst
.. _cn_api_paddle_i0e:
i0e
.. py:function:: paddle.i0e(x, name=None)
对于给定 x 计算其每个元素的第一类指数缩放零阶修正贝塞尔曲线函数,其中输入 x 大小无特殊限制。返回一个第一类指数缩放零阶修正贝塞尔曲线函数上的 Tensor。
.. math::
I_0(x)=\sum^{\infty}{k=0}\frac{(x^2/4)^k}{(k!)^2} \
I{0e}(x)=e^{-\lvert x\rvert}I_0(x)
参数
::::::::::
- x (Tensor) – 输入是一个多维的 Tensor,它的数据类型可以是 float32,float64。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name ,一般无需设置,默认值为 None。
关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
::::::::::
- Tensor (Tensor):在 x 处的第一类指数缩放零阶修正贝塞尔曲线函数的值。
代码示例
::::::::::
COPY-FROM: paddle.i0e
File: docs/api/paddle/i1_cn.rst
.. _cn_api_paddle_i1:
i1
.. py:function:: paddle.i1(x, name=None, *, out=None)
对于给定 x 计算其每个元素的第一类一阶修正贝塞尔曲线函数,其中输入 x 大小无特殊限制。返回第一类一阶修正贝塞尔函数对应输出 Tensor。
.. math::
I_1(x)=\frac{\left(\text { x }{i}\right)}{2} * \sum{k=0}^{\infty} \frac{\left(\text{x}_{i}^{2} / 4\right)^{k}}{(k !) *(k+1) !}
参数
::::::::::
- x (Tensor) – 输入是一个多维的 Tensor,它的数据类型可以是 float32,float64。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name ,一般无需设置,默认值为 None。
关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
::::::::::
- Tensor (Tensor):在 x 处的第一类一阶修正贝塞尔曲线函数的值。
代码示例
::::::::::
COPY-FROM: paddle.i1
File: docs/api/paddle/i1e_cn.rst
.. _cn_api_paddle_i1e:
i1e
.. py:function:: paddle.i1e(x, name=None, *, out=None)
对于给定 x 计算其每个元素的第一类指数缩放的一阶修正贝塞尔曲线函数,其中输入 x 大小无特殊限制。返回第一类指数缩放的一阶修正贝塞尔函数对应输出 Tensor。
.. math::
I_1e(x)=\exp (-|x|) * i 1(x)=\exp (-|x|) * \frac{\left(\text { input }{i}\right)}{2} * \sum{k=0}^{\infty} \frac{\left(\text { input }_{i}^{2} / 4\right)^{k}}{(k !) *(k+1) !}
参数
::::::::::
- x (Tensor) – 输入是一个多维的 Tensor,它的数据类型可以是 float32,float64。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name ,一般无需设置,默认值为 None。
关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
::::::::::
- Tensor (Tensor):在 x 处的第一类指数缩放的一阶修正贝塞尔曲线函数的值。
代码示例
::::::::::
COPY-FROM: paddle.i1e
File: docs/api/paddle/iinfo_cn.rst
[Binary file]
File: docs/api/paddle/imag_cn.rst
.. _cn_api_paddle_imag:
imag
.. py:function:: paddle.imag(x, name=None)
返回一个包含输入复数 Tensor 的虚部数值的新 Tensor。
参数
::::::::::::
- **x** (Tensor) - 输入的 Tensor,其数据类型可以为 complex64 或 complex128。别名 ``input``。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
Tensor,包含原复数 Tensor 的虚部数值。
代码示例
::::::::::::
COPY-FROM: paddle.imag
File: docs/api/paddle/in_dynamic_mode_cn.rst
.. _cn_api_paddle_in_dynamic_mode:
in_dynamic_mode
.. py:function:: paddle.in_dynamic_mode()
.. note::
从 2.0.0 版本开始,Paddle 默认开启动态图模式。
该接口查看 paddle 当前是否在动态图模式中运行。
可以通过 :ref:cn_api_paddle_enable_static 开启静态图模式,:ref:cn_api_paddle_disable_static 关闭静态图模式。
返回
::::::::::::
bool,如果 paddle 当前是在动态图模式运行,则返回 True,否则返回 False。
代码示例
::::::::::::
COPY-FROM: paddle.in_dynamic_mode
File: docs/api/paddle/increment_cn.rst
.. _cn_api_paddle_increment:
increment
.. py:function:: paddle.increment(x, value=1.0, name=None)
在控制流程中用来让参数 x 的数值增加 value。
参数
:::::::::
- x (Tensor) – 输入 Tensor,必须始终只有一个元素。支持的数据类型:float32、float64、int32、int64。
- value (float,可选) –
x的数值增量。默认值为 1.0。 - name (str,可选) - 具体用法请参见 :ref:
api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::
Tensor,形状和数据类型同输入 x。
代码示例
::::::::::::
COPY-FROM: paddle.increment
File: docs/api/paddle/index_add__cn.rst
.. cn_api_paddle_index_add:
index_add\_
.. py:function:: paddle.index_add_(x, index, axis, value, name=None)
Inplace 版本的 :ref:cn_api_paddle_index_add API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/index_add_cn.rst
.. _cn_api_paddle_index_add:
index_add
.. py:function:: paddle.index_add(x, index, axis, value, name=None)
沿着指定轴 axis 将 index 中指定位置的 x 与 value 相加,并写入到结果 Tensor 中的对应位置。这里 index 是一个 1-D Tensor。除 axis 轴外,返回的 Tensor 其余维度大小和输入 x 相等, axis 维度的大小等于 index 的大小。
示例
::
- 示例 1 (输入为 2-D Tensor, axis=0 ):
输入:
x.shape = [3, 3]
x.data = [[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]
参数:
index.shape = [2]
index.data = [0, 2]
axis = 0
value.shape = [2, 3]
value.data = [[1., 1., 1.],
[1., 1., 1.]]
输出:
out.shape = [3, 3]
out.data = [[2., 2., 2.],
[1., 1., 1.],
[2., 2., 2.]]
- 示例 2 (输入为 2-D Tensor, axis=1 ):
输入:
x.shape = [3, 3]
x.data = [[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]
参数:
index.shape = [2]
index.data = [0, 2]
axis = 1
value.shape = [3, 2]
value.data = [[1., 1.],
[1., 1.],
[1., 1.]]
输出:
out.shape = [3, 3]
out.data = [[2., 1., 2.],
[2., 1., 2.],
[2., 1., 2.]]示例 1 图解说明
下图展示了示例 1 中的情形——一个形状为 [3,3] 的二维张量通过 index_add 操作在 axis=0 轴上对指定位置的元素进行相加,同时保持了除 ``axis`` 轴外,返回的 Tensor 其余维度大小和输入 ``x`` 相等。
.. figure:: ../../images/api_legend/index_add/index_add-1.png
:width: 500
:alt: 示例 1 图示
:align: center示例 2 图解说明
下图展示了示例 2 中的情形——一个形状为 [3,3] 的二维张量通过 index_add 操作在 axis=1 轴上对指定位置的元素进行相加,同时保持了除 ``axis`` 轴外,返回的 Tensor 其余维度大小和输入 ``x`` 相等。
.. figure:: ../../images/api_legend/index_add/index_add-2.png
:width: 500
:alt: 示例 2 图示
:align: center参数
:::::::::
- **x** (Tensor) - 输入 Tensor。 ``x`` 的数据类型可以是 float16,float32,float64,int32,int64。
- **index** (Tensor) - 包含索引下标的 1-D Tensor。数据类型为 int32 或者 int64。
- **axis** (int) - 索引轴。数据类型为 int。
- **value** (Tensor) - 与 ``x`` 相加的 Tensor。 ``value`` 的数据类型同 ``x`` 。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
:::::::::
Tensor,返回一个数据类型同输入的 Tensor。
代码示例
::::::::::::
COPY-FROM: paddle.index_add
File: docs/api/paddle/index_fill__cn.rst
.. cn_api_paddle_index_fill:
index_fill\_
.. py:function:: paddle.index_fill_(x, index, axis, value, name=None)
Inplace 版本的 :ref:cn_api_paddle_index_fill API
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/index_fill_cn.rst
.. _cn_api_paddle_index_fill:
index_fill
.. py:function:: paddle.index_fill(x, index, axis, value, name=None)
依据指定的轴/维度和索引将指定位置的张量填充为指定值。
本 API 支持两种调用方式:
Paddle 风格:
paddle.index_fill(x, index, axis, value, name=None)
使用 Paddle 风格的参数顺序和命名。PyTorch 风格:
paddle.index_fill(input, dim, index, value)
使用 PyTorch 风格的参数顺序和命名。
图解说明:
一个形状为 [3, 3] 的二维张量,通过 index_fill 操作,当 axis = 0,索引张量 index 为 [0, 2],填充值 value = -1 时,将第一行和第三行的所有元素填充为 -1,从而得到形状仍为 [3, 3] 但元素部分改变的新张量。
.. figure:: ../../images/api_legend/index_fill.png
:width: 500
:align: center参数
:::::::::
- x (Tensor) – 输入张量。 x 的数据类型可以是 float16、 float32、 float64、 int32、 int64。
- index (Tensor) – 包含索引下标的 1-D Tensor。数据类型可以是 int32、 int64。
- axis (int) – 索引轴。数据类型为 int。
- value (float) – 用于填充目标张量的值。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::
Tensor,返回一个数据类型同输入的 Tensor。
代码示例
::::::::::::
COPY-FROM: paddle.index_fill
File: docs/api/paddle/index_put__cn.rst
.. cn_api_paddle_index_put:
index_put\_
.. py:function:: paddle.index_put_(x, indices, value, accumulate=False, name=None)
Inplace 版本的 :ref:cn_api_paddle_index_put API
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/index_put_cn.rst
[Binary file]
File: docs/api/paddle/index_sample_cn.rst
.. _cn_api_paddle_index_sample:
index_sample
.. py:function:: paddle.index_sample(x, index)
对输入 x 中的元素进行批量抽样,取 index 指定的对应下标的元素,按 index 中出现的先后顺序组织,填充为一个新的 Tensor。
x 与 index 都是 2-D Tensor。index 的第一维度与输入 x 的第一维度必须相同,index 的第二维度没有大小要求,可以重复索引相同下标元素。
参数
:::::::::
- **x** (Tensor)– 输入的二维 Tensor,数据类型为 int32、int64、bfloat16、float16、float32、float64。
- **index** (Tensor)– 包含索引下标的二维 Tensor。数据类型为 int32、int64。返回
:::::::::
Tensor,数据类型与输入 x 相同,维度与 index 相同。
代码示例
::::::::::::
COPY-FROM: paddle.index_sample
File: docs/api/paddle/index_select_cn.rst
[Binary file]
File: docs/api/paddle/inference_mode_cn.rst
.. _cn_api_paddle_inference_mode:
inference_mode
.. py:class:: paddle.inference_mode(mode=True)
创建一个上下文管理器或装饰器,用于启用或禁用推理模式。
在该模式下,每次计算的结果都将具有 stop_gradient=True。当 mode=False 时,将启用梯度计算。
也可以用作一个装饰器。
参数
::::::::::::
- **mode** (bool,可选) - 是否启用推理模式。默认值为 True。代码示例
::::::::::::
COPY-FROM: paddle.inference_mode
File: docs/api/paddle/inner_cn.rst
.. _cn_api_paddle_inner:
inner
.. py:function:: paddle.inner(x, y, name=None, *, out=None)
计算两个 Tensor 的内积。
对于 1 维 Tensor 计算普通内积,对于大于 1 维的 Tensor 计算最后一个维度的乘积和,此时两个输入 Tensor 最后一个维度长度需要相等。
参数
::::::::::::
- **x** (Tensor) - 一个 N 维 Tensor 或者标量 Tensor,如果是 N 维 Tensor 最后一个维度长度需要跟 y 保持一致。别名 ``input``。
- **y** (Tensor) - 一个 N 维 Tensor 或者标量 Tensor,如果是 N 维 Tensor 最后一个维度长度需要跟 x 保持一致。别名 ``other``。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。关键字参数
:::::::::
- **out** (Tensor,可选) - 输出 Tensor,若不为 ``None``,计算结果将保存在该 Tensor 中,默认值为 ``None``。返回
::::::::::::
- Tensor, x、y 的内积结果,Tensor shape 为 x.shape[:-1] + y.shape[:-1]。代码示例:
::::::::::
COPY-FROM: paddle.inner
File: docs/api/paddle/inverse_cn.rst
.. _cn_api_paddle_inverse:
inverse
.. py:function:: paddle.inverse(x, name=None, *, out=None)
计算方阵的逆矩阵。方阵是行数和列数相同的矩阵。输入可以是一个方阵(2-D Tensor)或者多个方阵组成的 batch(batch of square matrices)。
参数
::::::::::::
- x (Tensor) - 输入 Tensor,最后两个维度应相等。当维度大于 2 时,视为方阵的 batch。数据类型为 float32、float64、complex64、complex128。别名 input。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
关键字参数
::::::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
::::::::::::
Tensor,x 的逆矩阵,维度和数据类型与 x 相同。
代码示例
::::::::::::
COPY-FROM: paddle.inverse
File: docs/api/paddle/is_autocast_enabled_cn.rst
.. _cn_api_paddle_is_autocast_enabled:
is_autocast_enabled
.. py:function:: paddle.is_autocast_enabled(device_type=None)
获取当前上下文中是否启用了自动混合精度。
参数
::::::::::::
- **device_type** (str, 可选) - 设备类型,默认为 None。注意:在 PaddlePaddle 中所有设备共享同一套自动混合精度配置,实际返回值与设备类型无关。返回
::::::::::::
布尔值,如果当前上下文中启用了自动混合精度,则返回 True,否则返回 False。
代码示例
::::::::::::
COPY-FROM: paddle.is_autocast_enabled
File: docs/api/paddle/is_complex_cn.rst
.. _cn_api_paddle_is_complex:
is_complex
.. py:function:: paddle.is_complex(x)
判断输入 tensor 的数据类型是否为复数类型(complex64 或者 complex128)。
.. note::
别名支持: 参数名 input 可替代 x,如 input=tensor_x 等价于 x=tensor_x。
参数
:::::::::
- x (Tensor) - 输入 Tensor。别名:
input。
返回
:::::::::
bool,如果输入 tensor 的数据类型为复数类型则为 True,反之为 False
代码示例
:::::::::
COPY-FROM: paddle.is_complex
File: docs/api/paddle/is_empty_cn.rst
.. _cn_api_paddle_is_empty:
is_empty
.. py:function:: paddle.is_empty(x, name=None)
测试输入 Tensor x 是否为空。
参数
::::::::::::
- x (Tensor) - 测试的 Tensor。
- name (str,可选) - 具体用法请参见 :ref:
api_guide_Name,一般无需设置,默认值为 None。
返回
::::::::::::
Tensor,布尔类型的 Tensor,如果输入 Tensor x 为空则值为 True。
代码示例
::::::::::::
COPY-FROM: paddle.is_empty
File: docs/api/paddle/is_floating_point_cn.rst
.. _cn_api_paddle_is_floating_point:
is_floating_point
.. py:function:: paddle.is_floating_point(x)
判断输入 Tensor 的数据类型是否为浮点类型。
.. note::
别名支持: 参数名 input 可替代 x,如 is_floating_point(input=tensor_x) 等价于 is_floating_point(x=tensor_x) 。
参数
:::::::::
- **x** (Tensor) - 输入的 Tensor。别名: ``input``。返回
:::::::::
bool,输入 tensor 的数据类型为浮点数类型则为 True,反之为 False.
代码示例
:::::::::
COPY-FROM: paddle.is_floating_point
File: docs/api/paddle/is_grad_enabled_cn.rst
.. _cn_api_paddle_is_grad_enabled:
is_grad_enabled
.. py:function:: paddle.is_grad_enabled()
判断当前动态图下是否启用了计算梯度模式。
返回
:::::::::
bool,判断当前动态图是否启用了计算梯度的模式,若是则为 True,反之为 False。
代码示例
:::::::::
COPY-FROM: paddle.is_grad_enabled
File: docs/api/paddle/is_integer_cn.rst
.. _cn_api_paddle_is_integer:
is_integer
.. py:function:: paddle.is_integer(x)
判断输入 tensor 的数据类型是否为整数类型。
参数
:::::::::
- x (Tensor) - 输入 Tensor
返回
:::::::::
bool,输入 tensor 的数据类型为整数类型则为 True,反之为 False
代码示例
:::::::::
COPY-FROM: paddle.is_integer
File: docs/api/paddle/is_tensor_cn.rst
.. _cn_api_paddle_is_tensor:
is_tensor
.. py:function:: paddle.is_tensor(x)
测试输入对象是否是 paddle.Tensor
.. note::
别名支持: 参数名 obj 可替代 x,如 is_tensor(obj=tensor_x) 等价于 is_tensor(x=tensor_x) 。
参数
::::::::::::
- **x** (Object) - 测试的对象。别名: ``obj``。返回
::::::::::::
bool 值,如果 x 是 paddle.Tensor 类型返回 True,反之返回 False。
代码示例
::::::::::::
COPY-FROM: paddle.is_tensor
File: docs/api/paddle/isclose_cn.rst
[Binary file]
File: docs/api/paddle/isfinite_cn.rst
.. _cn_api_paddle_isfinite:
isfinite
.. py:function:: paddle.isfinite(x, name=None)
返回输入 Tensor 的每一个值是否为有限值(既非 +/-INF 也非 +/-NaN )。
.. note::
别名支持: 参数名 input 可替代 x,如 input=tensor_x 等价于 x=tensor_x。
参数
:::::::::
- x (Tensor):输入的 Tensor,数据类型为:float16、float32、float64、int32、int64、complex64、complex128。
别名: input
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::Tensor,每个元素是一个 bool 值,表示输入 x 的每个元素是否为有限值(既非 +/-INF 也非 +/-NaN )。
代码示例
:::::::::
COPY-FROM: paddle.isfinite
File: docs/api/paddle/isin_cn.rst
.. _cn_api_paddle_isin:
isin
.. py:function:: paddle.isin(x, test_x, assume_unique=False, invert=False, name=None)
检验 x 中的每一个元素是否在 test_x 中。
.. note::
别名支持: 参数名 elements 可替代 x,参数名 test_elements 可替代 test_x,如 isin(elements=tensor1, test_elements=tensor2) 等价于 isin(x=tensor1, test_x=tensor2) 。
参数
:::::::::
- x (Tensor) - 输入的 tensor,数据类型为:'bfloat16', 'float16', 'float32', 'float64', 'int32', 'int64'。别名: elements。
- test_x (Tensor) - 用于检验的 tensor,数据类型为:'bfloat16', 'float16', 'float32', 'float64', 'int32', 'int64'。别名: test_elements。
- assume_unique (bool,可选) - 如果设置为 True,表示 x 与 test_x 的元素均是唯一的,这种情况可以提升计算的速度。默认值为 False。
- invert (bool,可选) - 是否输出反转的结果。如果为 True,表示将结果反转。默认值为 False。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::Tensor,输出的 tensor 与输入 x 形状相同。
代码示例
:::::::::
COPY-FROM: paddle.isin
File: docs/api/paddle/isinf_cn.rst
.. _cn_api_paddle_isinf:
isinf
.. py:function:: paddle.isinf(x, name=None)
返回输入 tensor 的每一个值是否为 +/-INF 。
.. note::
别名支持: 参数名 input 可替代 x,如 input=tensor_x 等价于 x=tensor_x。
参数
:::::::::
- x (Tensor):输入的 Tensor,数据类型为:float16、float32、float64、uint8、int8、int16、int32、int64、complex64、complex128。
别名: input
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::Tensor,每个元素是一个 bool 值,表示输入 x 的每个元素是否为 +/-INF 。
代码示例
:::::::::
COPY-FROM: paddle.isinf
File: docs/api/paddle/isnan_cn.rst
.. _cn_api_paddle_isnan:
isnan
.. py:function:: paddle.isnan(x, name=None)
返回输入 tensor 的每一个值是否为 +/-NaN 。
.. note::
别名支持: 参数名 input 可替代 x,如 input=tensor_x 等价于 x=tensor_x。
参数
:::::::::
- x (Tensor) - 输入的 Tensor,数据类型为:float16、float32、float64、int32、int64、complex64、complex128。
别名: input
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::Tensor,每个元素是一个 bool 值,表示输入 x 的每个元素是否为 +/-NaN 。
代码示例
:::::::::
COPY-FROM: paddle.isnan
File: docs/api/paddle/isneginf_cn.rst
.. _cn_api_paddle_isneginf:
isneginf
.. py:function:: paddle.isneginf(x, name=None, *, out=None)
返回输入 tensor 的每一个值是否为 -INF 。
参数
:::::::::
- x (Tensor):输入的 Tensor,数据类型为:float16、float32、float64、int8、int16、int32、int64、uint8。别名: input。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
:::::::::Tensor,每个元素是一个 bool 值,表示输入 x 的每个元素是否为 -INF 。
代码示例
:::::::::
COPY-FROM: paddle.isneginf
File: docs/api/paddle/isposinf_cn.rst
.. _cn_api_paddle_isposinf:
isposinf
.. py:function:: paddle.isposinf(x, name=None, *, out=None)
返回输入 tensor 的每一个值是否为 +INF 。
参数
:::::::::
- x (Tensor):输入的 Tensor,数据类型为:bfloat16、float16、float32、float64、int8、int16、int32、int64、uint8。别名: input。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
:::::::::Tensor,每个元素是一个 bool 值,表示输入 x 的每个元素是否为 +INF 。
代码示例
:::::::::
COPY-FROM: paddle.isposinf
File: docs/api/paddle/isreal_cn.rst
.. _cn_api_paddle_isreal:
isreal
.. py:function:: paddle.isreal(x, name=None)
判断输入 tensor 的每一个值是否为实数类型(非 complex64 或者 complex128)。
参数
:::::::::
- x (Tensor) - 输入 Tensor。别名:
input。 - name (str,可选) - 具体用法请参见 :ref:
api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::Tensor,每个元素是一个 bool 值,表示输入 x 的每个元素是否为实数类型。
代码示例
:::::::::
COPY-FROM: paddle.isreal
File: docs/api/paddle/kaiser_window_cn.rst
.. _cn_api_paddle_kaiser_window:
kaiser_window
.. py:function:: paddle.kaiser_window(window_length, periodic=True, beta=12.0, *, dtype='float32', layout=None, device=None, pin_memory=False, requires_grad=False, out=None)
计算 Kaiser 窗。
参数
::::::::::::
- **window_length** (int) - 返回窗的长度,必须为正数。
- **periodic** (bool,可选) - 若为 True,则返回适用于周期函数的窗;若为 False,则返回对称窗。默认值为 True。
- **beta** (float,可选) - 窗函数的形状参数。默认值为 12.0。关键字参数
::::::::::::
- **dtype** (str,可选) - 返回 Tensor 的数据类型。默认值为 ``'float32'``。
- **layout** (str,可选) - 仅为与 PyTorch API 保持一致而保留,在 Paddle 中会被忽略。默认值为 None。
- **device** (PlaceLike|None,可选) - 返回 Tensor 所在的设备。若为 None,则使用当前设备。默认值为 None。
- **pin_memory** (bool,可选) - 是否将返回 Tensor 分配在锁页内存中,仅对 CPU Tensor 生效。默认值为 False。
- **requires_grad** (bool,可选) - 是否为返回 Tensor 记录自动求导。默认值为 False。
- **out** (Tensor,可选) - 输出 Tensor,若不为 ``None``,计算结果将保存在该 Tensor 中,默认值为 ``None``。返回
::::::::::::
Tensor:形状为 (window_length,) 的一维 Tensor,包含 Kaiser 窗。
代码示例
::::::::::::
COPY-FROM: paddle.kaiser_window
File: docs/api/paddle/kron_cn.rst
[Binary file]
File: docs/api/paddle/kthvalue_cn.rst
.. _cn_api_paddle_kthvalue:
kthvalue
.. py:function:: paddle.kthvalue(x, k, axis=None, keepdim=False, name=None, *, out=None)
在指定的轴上查找第 k 小的元素和其对应所在的索引信息。
参数
:::::::::
- x (Tensor) - 一个输入的 N-D Tensor,支持的数据类型:float16、float32、float64、int32、int64。别名 input。
- k (int,Tensor) - 需要沿轴查找的第 k 小,所对应的 k 值。
- axis (int,可选) - 指定对输入 Tensor 进行运算的轴,axis 的有效范围是[-R, R),R 是输入 x 的 Rank, axis 为负时与 axis + R 等价。默认值为-1。别名 dim。
- keepdim (bool,可选)- 是否保留指定的轴。如果是 True,维度会与输入 x 一致,对应所指定的轴的 size 为 1。否则,由于对应轴被展开,输出的维度会比输入小 1。默认值为 False。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
:::::::::
tuple(Tensor),返回第 k 小的元素和对应的索引信息。结果的数据类型和输入 x 一致。索引的数据类型是 int64。
代码示例
:::::::::
COPY-FROM: paddle.kthvalue
File: docs/api/paddle/LazyGuard_cn.rst
.. _cn_api_paddle_LazyGuard:
LazyGuard
.. py:class:: paddle.LazyGuard()
LazyGuard 是一个用于设置模型(继承自 paddle.nn.Layer ) 中参数延迟初始化的上下文管理器。配合使用 python 的 with 语句来将 with LazyGuard(): 代码块下所有模型在实例化时,其内部的参数均不会立即申请内存空间。
代码示例
::::::::::::
COPY-FROM: paddle.LazyGuard
File: docs/api/paddle/lcm__cn.rst
.. cn_api_paddle_lcm:
lcm\_
.. py:function:: paddle.lcm_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_lcm API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/lcm_cn.rst
.. _cn_api_paddle_lcm:
lcm
.. py:function:: paddle.lcm(x, y, name=None)
计算两个输入的按元素绝对值的最小公倍数,输入必须是整型。
.. note::
lcm(0,0)=0, lcm(0, y)=0
如果 x 和 y 的 shape 不一致,会对两个 shape 进行广播操作,得到一致的 shape(并作为输出结果的 shape),
请参见 `Tensor 介绍`_ .
.. _Tensor 介绍: ../../guides/beginner/tensor_cn.html#id7参数
:::::::::
- **x** (Tensor) - 输入的 Tensor,数据类型为:int32,int64。支持别名 ``input`` 。
- **y** (Tensor) - 输入的 Tensor,数据类型为:int32,int64。支持别名 ``other`` 。
- **name** (str,可选) - 操作的名称(可选,默认值为 None)。更多信息请参见 :ref:`api_guide_Name`。返回
:::::::::
输出 Tensor,与输入数据类型相同。
代码示例
:::::::::
COPY-FROM: paddle.lcm
File: docs/api/paddle/ldexp__cn.rst
.. cn_api_paddle_ldexp:
ldexp\_
.. py:function:: paddle.ldexp_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_ldexp API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/ldexp_cn.rst
.. _cn_api_paddle_ldexp:
ldexp
.. py:function:: paddle.ldexp(x, y, name=None, *, out=None)
计算 x 乘以 2 的 y 次幂
.. math::
out = x * 2^{y}
参数
::::::::::::
- **x** (Tensor) - 多维 Tensor。数据类型为 float32、float64、int32、int64。别名:``input``。
- **y** (Tensor) - 多维 Tensor。通常为整数。别名:``other``。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
::::::::::::
输出为 Tensor,如果 x, y 有不同的形状并且是可广播的,那么产生的张量形状是广播后 x 和 y 的形状。如果 x, y 有相同的形状,其形状与 x, y 相同。数据类型是 float32 或 float64。
代码示例
::::::::::::
COPY-FROM: paddle.ldexp
File: docs/api/paddle/lerp__cn.rst
.. cn_api_paddle_lerp:
lerp\_
.. py:function:: paddle.lerp_(x, y, weight, name=None)
Inplace 版本的 :ref:cn_api_paddle_lerp API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/lerp_cn.rst
.. _cn_api_paddle_lerp:
lerp
.. py:function:: paddle.lerp(x, y, weight, name=None, *, out=None)
基于给定的 weight 计算 x 与 y 的线性插值
.. math::
lerp(x, y, weight) = x + weight * (y - x)
参数
:::::::::
- **x** (Tensor) - 输入的 Tensor,作为线性插值开始的点,数据类型为:bfloat16、float16、float32、float64。别名 ``input``。
- **y** (Tensor) - 输入的 Tensor,作为线性插值结束的点,数据类型为:bfloat16、float16、float32、float64。别名 ``end``。
- **weight** (float|Tensor) - 给定的权重值,weight 为 Tensor 时数据类型为:bfloat16、float16、float32、float64。
- **name** (str,可选) - 操作的名称(可选,默认值为 None)。更多信息请参见 :ref:`api_guide_Name`。关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
:::::::::
输出 Tensor,与 x 数据类型相同。
代码示例
:::::::::
COPY-FROM: paddle.lerp
File: docs/api/paddle/less__cn.rst
.. cn_api_paddle_less:
less\_
.. py:function:: paddle.less_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_less API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/less_cn.rst
.. _cn_api_paddle_less:
less
.. py:function:: paddle.less(x, y, name=None)
逐元素地返回 :math:x < y 的逻辑值,相同位置前者输入小于后者输入则返回 True,否则返回 False。使用重载算子 < 可以有相同的计算函数效果。
.. note::
输出的结果不返回梯度。
参数
::::::::::::
- **x** (Tensor) - 输入 Tensor,支持的数据类型包括 bool、bfloat16、float16、float32、float64、uint8、int8、int16、int32、int64。
- **y** (Tensor) - 输入 Tensor,支持的数据类型包括 bool、bfloat16、float16、float32、float64、uint8、int8、int16、int32、int64。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
输出结果的 Tensor,输出 Tensor 的 shape 和输入一致,Tensor 数据类型为 bool。
代码示例
::::::::::::
COPY-FROM: paddle.less
File: docs/api/paddle/less_equal__cn.rst
.. cn_api_paddle_less_equal:
less\_equal\_
.. py:function:: paddle.less_equal_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_less_equal API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/less_equal_cn.rst
.. _cn_api_paddle_less_equal:
less_equal
.. py:function:: paddle.less_equal(x, y, name=None)
逐元素地返回 :math:x <= y 的逻辑值,相同位置前者输入小于等于后者输入则返回 True,否则返回 False。使用重载算子 <= 可以有相同的计算函数效果。
.. note::
输出的结果不返回梯度。
参数
::::::::::::
- **x** (Tensor) - 输入 Tensor,支持的数据类型包括 bool、bfloat16、float16、float32、float64、uint8、int8、int16、int32、int64。
- **y** (Tensor) - 输入 Tensor,支持的数据类型包括 bool、bfloat16、float16、float32、float64、uint8、int8、int16、int32、int64。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
输出结果的 Tensor,输出 Tensor 的 shape 和输入一致,Tensor 数据类型为 bool。
代码示例
::::::::::::
COPY-FROM: paddle.less_equal
File: docs/api/paddle/less_than__cn.rst
.. cn_api_paddle_less_than:
less\_than\_
.. py:function:: paddle.less_than_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_less_than API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/less_than_cn.rst
.. _cn_api_paddle_less_than:
less_than
.. py:function:: paddle.less_than(x, y, name=None)
逐元素地返回 :math:x < y 的逻辑值,相同位置前者输入小于后者输入则返回 True,否则返回 False。使用重载算子 < 可以有相同的计算函数效果。
.. note::
输出的结果不返回梯度。
参数
::::::::::::
- **x** (Tensor) - 输入 Tensor,支持的数据类型包括 bool、bfloat16、float16、float32、float64、uint8、int8、int16、int32、int64。
- **y** (Tensor) - 输入 Tensor,支持的数据类型包括 bool、bfloat16、float16、float32、float64、uint8、int8、int16、int32、int64。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
输出结果的 Tensor,输出 Tensor 的 shape 和输入一致,Tensor 数据类型为 bool。
代码示例
::::::::::::
COPY-FROM: paddle.less_than
File: docs/api/paddle/lgamma__cn.rst
.. cn_api_paddle_lgamma:
lgamma\_
.. py:function:: paddle.lgamma_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_lgamma API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/lgamma_cn.rst
.. _cn_api_paddle_lgamma:
lgamma
.. py:function:: paddle.lgamma(x, name=None)
计算输入 x 的 gamma 函数的自然对数并返回。
参数
:::::::::
- x (Tensor) - 输入的 Tensor,数据类型为:float32、float64。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
返回
:::::::::
输出 Tensor,与 x 维度相同、数据类型相同。
代码示例
:::::::::
COPY-FROM: paddle.lgamma
File: docs/api/paddle/linspace_cn.rst
.. _cn_api_paddle_linspace:
linspace
.. py:function:: paddle.linspace(start, stop, num, dtype=None, name=None)
返回一个 Tensor,Tensor 的值为在区间 start 和 stop 上均匀间隔的 num 个值,输出 Tensor 的长度为 num。
注意:不进行梯度计算
参数
::::::::::::
- **start** (int|float|Tensor) – ``start`` 是区间开始的变量,可以是一个 int、float,或是一个 shape 为[0]的 Tensor,该 Tensor 的数据类型可以是 int32,int64,float32,float64。
- **stop** (int|float|Tensor) – ``stop`` 是区间结束的变量,可以是一个 int、float,或是一个 shape 为[0]的 Tensor,该 Tensor 的数据类型可以是 int32,int64,float32,float64。
- **num** (int|Tensor) – ``num`` 是给定区间内需要划分的区间数,可以是一个 int,或是一个 shape 为[0]的 Tensor,该 Tensor 的数据类型需为 int32。
- **dtype** (str|paddle.dtype|np.dtype,可选) – 输出 Tensor 的数据类型,可以是 int32,int64,float32,float64。如果 dtype 的数据类型为 None,输出 Tensor 数据类型为 float32。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
表示等间隔划分结果的 1-D Tensor,该 Tensor 的 shape 大小为 :math:[num],在 num 为 1 的情况下,仅返回包含 start 元素值的 Tensor。
代码示例
::::::::::::
COPY-FROM: paddle.linspace
File: docs/api/paddle/load_cn.rst
.. _cn_api_paddle_load:
load
.. py:function:: paddle.load(path, **configs)
从指定路径载入可以在 paddle 中使用的对象实例。
.. note::
目前支持载入:Layer 或者 Optimizer 的 state_dict,Tensor 以及包含 Tensor 的嵌套 list、tuple、dict、Program。对于 Tensor 对象,只保存了它的名字和数值,没有保存 stop_gradient 等属性,如果您需要这些没有保存的属性,请调用 set_value 接口将数值设置到带有这些属性的 Tensor 中。
遇到使用问题,请参考:
.. toctree::
:maxdepth: 1
../../../../faq/save_cn.md参数
:::::::::
- path (str|BytesIO) - 载入目标对象实例的路径/内存对象。通常该路径是目标文件的路径,当从用于存储预测模型 API 的存储结果中载入 state_dict 时,该路径可能是一个文件前缀或者目录。
- **configs (dict,可选) - 其他用于兼容的载入配置选项。这些选项将来可能被移除,如果不是必须使用,不推荐使用这些配置选项。默认为 None。目前支持以下配置选项:
- (1) model_filename (str) - paddle 1.x 版本 ``save_inference_model`` 接口存储格式的预测模型文件名,原默认文件名为 ``__model__`` ;
- (2) params_filename (str) - paddle 1.x 版本 ``save_inference_model`` 接口存储格式的参数文件名,没有默认文件名,默认将各个参数分散存储为单独的文件;
- (3) return_numpy(bool) - 如果被指定为 ``True`` ,``load`` 的结果中的 Tensor 会被转化为 ``numpy.ndarray``,默认为 ``False`` 。返回
:::::::::
Object,一个可以在 paddle 中使用的对象实例。
代码示例 1
:::::::::
COPY-FROM: paddle.load:code-example-1
代码示例 2
:::::::::
COPY-FROM: paddle.load:code-example-2
代码示例 3
:::::::::
COPY-FROM: paddle.load:code-example-3
代码示例 4
:::::::::
COPY-FROM: paddle.load:code-example-4
代码示例 5
:::::::::
COPY-FROM: paddle.load:code-example-5
File: docs/api/paddle/log10__cn.rst
.. cn_api_paddle_log10:
log10\_
.. py:function:: paddle.log10_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_log10 API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/log10_cn.rst
.. _cn_api_paddle_log10:
log10
.. py:function:: paddle.log10(x, name=None)
Log10 激活函数(逐元素计算底为 10 的对数)
.. math::
\Out=log_{10} x\
参数
::::::::::::
- x (Tensor) – 输入的 Tensor。数据类型为 int32、int64、float16、bfloat16、float32、float64、complex64 或 complex128。
- name (str,可选) - 具体用法请参见 :ref:
api_guide_Name,一般无需设置,默认值为 None。
返回
::::::::::::
Tensor,Log10 算子底为 10 对数输出,数据类型与输入一致。
代码示例
::::::::::::
COPY-FROM: paddle.log10
File: docs/api/paddle/log1p_cn.rst
.. _cn_api_paddle_log1p:
log1p
.. py:function:: paddle.log1p(x, name=None)
计算 Log1p(自然对数 + 1)结果。
.. math::
\Out=ln(x+1)\
参数
::::::::::::
- x (Tensor) – 输入为一个多维的 Tensor,数据类型为 int32,int64,float16,bfloat16,float32, float64, complex64 或 complex128。
- name (str,可选) - 具体用法请参见 :ref:
api_guide_Name,一般无需设置,默认值为 None。
返回
::::::::::::
计算 x 的自然对数 + 1 后的 Tensor,数据类型,形状与 x 一致。
代码示例
::::::::::::
COPY-FROM: paddle.log1p
File: docs/api/paddle/log2__cn.rst
.. cn_api_paddle_log2:
log2\_
.. py:function:: paddle.log2_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_log2 API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/log2_cn.rst
.. _cn_api_paddle_log2:
log2
.. py:function:: paddle.log2(x, name=None, *, out)
Log2 激活函数(计算底为 2 的对数)
.. math::
\Out=log_2x\
.. note::
别名支持: 参数名 input 可替代 x;
参数
:::::::::
- x (Tensor) – 该 OP 的输入为 Tensor。数据类型为 int32,int64,float16,bfloat16,float32, float64, complex64 或 complex128。
别名:input - name (str,可选) - 具体用法请参见 :ref:
api_guide_Name,一般无需设置,默认值为 None。 - out (Tensor,可选) - 输出的结果。该参数为仅关键字参数,默认值为 None。
返回
:::::::::
Tensor,Log2 算子底为 2 对数输出,数据类型与输入一致。
代码示例
:::::::::
COPY-FROM: paddle.log2
File: docs/api/paddle/log__cn.rst
.. cn_api_paddle_log:
log\_
.. py:function:: paddle.log_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_log API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/log_cn.rst
.. _cn_api_paddle_log:
log
.. py:function:: paddle.log(x, name=None, *, out=None)
Log 激活函数(计算自然对数)
.. math::
\Out=ln(x)\
参数
::::::::::::
- x (Tensor) – 输入为 Tensor。数据类型只能为 int32,int64,float16,bfloat16,float32, float64, complex64 或 complex128。别名
input。 - name (str,可选) - 具体用法请参见 :ref:
api_guide_Name,一般无需设置,默认值为 None。
关键字参数
:::::::::
- **out** (Tensor,可选) - 输出 Tensor,若不为 ``None``,计算结果将保存在该 Tensor 中,默认值为 ``None``。返回
::::::::::::
Tensor, Log 算子自然对数输出,数据类型与输入一致。
代码示例
::::::::::::
COPY-FROM: paddle.log
File: docs/api/paddle/log_normal__cn.rst
.. cn_api_paddle_log_normal:
log\_normal\_
.. py:function:: paddle.log_normal_(x, mean=1.0, std=2.0, name=None)
Inplace 版本的 :ref:cn_api_paddle_log_normal API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/log_normal_cn.rst
[Binary file]
File: docs/api/paddle/logaddexp_cn.rst
.. _cn_api_paddle_logaddexp:
logaddexp
.. py:function:: paddle.logaddexp(x, y, name=None, *, out=None)
计算 x 和 y 的以 e 为底的指数的和的自然对数。计算公式如下:
.. math::
logaddexp(x) = \log (exp(x)+exp(y))
参数
::::::::::
- x (Tensor) - 输入的 Tensor,数据类型为:int32,int64,bfloat16,float16,float32、float64。别名 input。
- y (Tensor) - 输入的 Tensor,数据类型为:int32,int64,bfloat16,float16,float32、float64。别名 other。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
关键字参数
::::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
::::::::::
Tensor,根据上述公式计算的 logaddexp(x) 结果
代码示例
::::::::::
COPY-FROM: paddle.logaddexp
File: docs/api/paddle/logcumsumexp_cn.rst
.. _cn_api_paddle_logcumsumexp:
logcumsumexp
.. py:function:: paddle.logcumsumexp(x, axis=None, dtype=None, name=None, *, out=None)
计算 x 的指数的前缀和的对数。
假设输入是二维矩阵,j 是 axis 维的下标,i 是另一维的下标,那么运算结果将是
.. math::
logcumsumexp(x)_{ij} = log \sum_{i=0}^{j}exp(x_{ij}).. note::
结果的第一个元素和输入的第一个元素相同。
参数
:::::::::
- x (Tensor) - 需要进行操作的 Tensor,数据类型为 float32、float64、float16、bfloat16、uint8、int8、int16、int32、int64。别名 input。
- axis (int,可选) - 指明需要计算的维度。-1 代表最后一维。默认:None,将输入展开为一维变量再进行计算。别名 dim。
- dtype (str|paddle.dtype|np.dtype,可选) - 输出 Tensor 的数据类型,支持 float16、float32、float64。如果指定了,那么在执行操作之前,输入 Tensor 将被转换为 dtype。这对于防止数据类型溢出非常有用。默认为:None。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
关键字参数
:::::::::
- out (Tensor,可选) - 输出 Tensor,若不为 None,计算结果将保存在该 Tensor 中,默认值为 None。
返回
:::::::::
- Tensor (Tensor),x 的指数的前缀和的对数(整数输入类型会自动转换为 float32)。
代码示例
:::::::::
COPY-FROM: paddle.logcumsumexp
File: docs/api/paddle/logdet_cn.rst
.. _cn_api_paddle_logdet:
logdet
.. py:function:: paddle.logdet(input, name=None)
计算一个或一批方阵的行列式的自然对数。
对于行列式为负数的矩阵,返回 nan。
对于行列式为零的矩阵,返回 -inf。
参数
::::::::::::
- **input** (Tensor) - 输入一个或批量方阵。``input`` 的形状应为 ``[*, n, n]``,其中 ``*`` 为零或更大的批次维度。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
Tensor:输出矩阵的行列式的自然对数值,Shape 为 [*]。
代码示例
::::::::::::
COPY-FROM: paddle.logdet
File: docs/api/paddle/logical_and__cn.rst
.. cn_api_paddle_logical_and:
logical_and\_
.. py:function:: paddle.logical_and_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_logical_and API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/logical_and_cn.rst
[Binary file]
File: docs/api/paddle/logical_not__cn.rst
.. cn_api_paddle_logical_not:
logical\_not\_
.. py:function:: paddle.logical_not_(x, name=None)
Inplace 版本的 :ref:cn_api_paddle_logical_not API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/logical_not_cn.rst
.. _cn_api_paddle_logical_not:
logical_not
.. py:function:: paddle.logical_not(x, out=None, name=None)
逐元素的对 X Tensor 进行逻辑非运算
.. math::
Out = !X
.. note::
别名支持: 参数名 input 可替代 x。
参数
::::::::::::
- **x** (Tensor) - 逻辑非运算的输入,是一个 Tensor,支持的数据类型为 bool, int8, int16, int32, int64, bfloat16, float16, float32, float64, complex64, complex128。
别名: ``input``
- **out** (Tensor,可选) - 指定算子输出结果的 Tensor,可以是程序中已经创建的任何 Tensor。默认值为 None,此时将创建新的 Tensor 来保存输出结果。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
Tensor,与 x 维度相同,数据类型相同。
代码示例
::::::::::::
COPY-FROM: paddle.logical_not
File: docs/api/paddle/logical_or__cn.rst
.. cn_api_paddle_logical_or:
logical_or\_
.. py:function:: paddle.logical_or_(x, y, name=None)
Inplace 版本的 :ref:cn_api_paddle_logical_or API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/logical_or_cn.rst
[Binary file]
File: docs/api/paddle/logical_xor_cn.rst
[Binary file]
File: docs/api/paddle/logit__cn.rst
.. cn_api_paddle_logit:
logit\_
.. py:function:: paddle.logit_(x, eps=None, name=None)
Inplace 版本的 :ref:cn_api_paddle_logit API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/logit_cn.rst
[Binary file]
File: docs/api/paddle/logspace_cn.rst
[Binary file]
File: docs/api/paddle/logsumexp_cn.rst
.. _cn_api_paddle_logsumexp:
logsumexp
.. py:function:: paddle.logsumexp(x, axis=None, keepdim=False, name=None, *, out=None)
沿着参数 axis 计算 x 的以 e 为底的指数的和的自然对数。计算公式如下:
.. math::
logsumexp(x) = \log\sum exp(x)
.. note::
别名支持: 参数名 input 可替代 x, dim 可替代 axis。
参数
::::::::::
- x (Tensor) - 输入的 Tensor,数据类型为:float16,float32、float64,维度不超过 4 。
别名: input
- axis (int|list|tuple,可选) - 指定对 x 进行计算的轴。axis 可以是 int、list(int)、tuple(int)。如果 axis 包含多个维度,则沿着 axis 中的所有轴进行计算。axis 或者其中的元素值应该在范围[-D, D)内,D 是 x 的维度。如果 axis 或者其中的元素值小于 0,则等价于 :math:axis + D。如果 axis 是 None,则对 x 的全部元素计算 logsumexp。默认值为 None。
别名: dim
- keepdim (bool,可选) - 是否在输出 Tensor 中保留减小的维度。如果 keepdim 为 True,则输出 Tensor 和 x 具有相同的维度(减少的维度除外,减少的维度的大小为 1)。否则,输出 Tensor 的形状会在 axis 上进行 squeeze 操作。默认值为 False。
- name (str,可选) - 具体用法请参见 :ref:api_guide_Name,一般无需设置,默认值为 None。
- out (Tensor,可选) - 指定输出结果的 Tensor,默认值为 None。
返回
::::::::::
Tensor,沿着 axis 进行 logsumexp 计算的结果,数据类型和 x 相同。
代码示例
::::::::::
COPY-FROM: paddle.logsumexp
File: docs/api/paddle/masked_fill__cn.rst
.. cn_api_paddle_masked_fill:
masked_fill\_
.. py:function:: paddle.masked_fill_(x, mask, value, name=None)
Inplace 版本的 :ref:cn_api_paddle_masked_fill API,对输入 x 采用 Inplace 策略。
.. note::
别名支持:参数名 input 可替代 x,如 masked_fill_(input=tensor_x, mask=tensor_mask, value=val) 等价于 masked_fill_(x=tensor_x, mask=tensor_mask, value=val)。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/masked_fill_cn.rst
.. _cn_api_paddle_masked_fill:
masked_fill
.. py:function:: paddle.masked_fill(x, mask, value, name=None)
在 mask 为 True 的位置用 value 填充 x 中的元素。mask 的形状必须与 x 的形状可广播。
下图展示了一个例子:假设我们有一个所有元素值为 1 的 3x3 矩阵 x 和一个相同尺寸的掩码矩阵 Mask,Value 值为 3。
.. image:: ../../images/api_legend/masked_fill.png
:width: 700
:alt: 图例
参数
::::::::::::
- **x** (Tensor) - 输入 Tensor,数据类型为 float,double,int,int64_t,float16 或者 bfloat16。别名 ``input``。
- **mask** (Tensor) - 布尔张量,表示要填充的位置。mask 的形状必须与 x 的形状可广播。mask 的数据类型必须为 bool。
- **value** (Scalar or 0-D Tensor) - 用于填充目标张量的值,数据类型为 float,double,int,int64_t,float16 或者 bfloat16。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
Tensor,与 x 具有相同形状和数据类型的 Tensor。
代码示例
::::::::::::
COPY-FROM: paddle.masked_fill
File: docs/api/paddle/masked_scatter__cn.rst
.. cn_api_paddle_masked_scatter:
masked_scatter\_
.. py:function:: paddle.masked_scatter_(x, mask, value, name=None)
Inplace 版本的 :ref:cn_api_paddle_masked_scatter API,对输入 x 采用 Inplace 策略。
更多关于 inplace 操作的介绍请参考 3.1.3 原位(Inplace)操作和非原位操作的区别_ 了解详情。
.. _3.1.3 原位(Inplace)操作和非原位操作的区别: https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/guides/beginner/tensor_cn.html#id3
File: docs/api/paddle/masked_scatter_cn.rst
.. _cn_api_paddle_masked_scatter:
masked_scatter
.. py:function:: paddle.masked_scatter(x, mask, value, name=None)
返回一个 N-D 的 Tensor,Tensor 的值是根据 mask 信息,将 value 中的值逐个填充到 x 中 mask 对应为 True 的位置,mask 的数据类型是 bool。
示例图解说明:
- value 张量:包含要填充到目标张量中的数据。只有掩码为 True 的部分会从 value 中取值,其余值会被忽略。
- mask 掩码:指定哪些位置需要从 value 张量中提取值并填充到目标张量中。True 表示对应位置需要被更新。
- origin 原始张量:输入张量,只有满足掩码的部分会被替换,其余部分保持不变。
- 操作结果:经过 masked_scatter 操作,origin 张量中掩码为 True 的部分被更新为 value 中对应的值,而掩码为 False 的部分保持不变,形成最终更新的张量。
.. figure:: ../../images/api_legend/masked_scatter.png
:width: 500
:alt: 示例一图示
:align: center参数
::::::::::::
- **x** (Tensor) - 输入 Tensor,数据类型为 float,double,int,int64_t,float16 或者 bfloat16。
- **mask** (Tensor) - 布尔张量,表示要填充的位置。mask 的数据类型必须为 bool。
- **value** (Tensor) - 用于填充目标张量的值,数据类型为 float,double,int,int64_t,float16 或者 bfloat16。
- **name** (str,可选) - 具体用法请参见 :ref:`api_guide_Name`,一般无需设置,默认值为 None。返回
::::::::::::
返回